package com.ctshk.rpc.custom.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.Currency;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.req.MainData;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.custom.dto.insurance.TripScheduleInsuranceDTO;
import com.ctshk.rpc.custom.dto.trip.*;
import com.ctshk.rpc.custom.dto.trip.TripScheduleDetailInfoResp;
import com.ctshk.rpc.custom.entity.*;
import com.ctshk.rpc.custom.mapper.*;
import com.ctshk.rpc.custom.req.ContactReq;
import com.ctshk.rpc.custom.req.QuotationTouristTypeReq;
import com.ctshk.rpc.custom.req.quotation.*;
import com.ctshk.rpc.custom.req.trip.*;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleTouristCountService;
import com.ctshk.rpc.guide.dto.GroupInfoDTO;
import com.ctshk.rpc.guide.enums.GroupDistributionGroupType;
import com.ctshk.rpc.guide.req.GroupDistributionAddReq;
import com.ctshk.rpc.guide.req.GroupDistributionIdUpdateStatusReq;
import com.ctshk.rpc.guide.req.TeaPartyAddReq;
import com.ctshk.rpc.guide.service.IGroupDistributionService;
import com.ctshk.rpc.guide.service.ITeaPartyService;
import com.ctshk.rpc.insurance.dto.InsuranceDTO;
import com.ctshk.rpc.insurance.service.IInsuranceService;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderTouristRefundService;
import com.ctshk.rpc.system.dto.*;
import com.ctshk.rpc.system.dto.mian.data.MainDataDeductionRulesDTO;
import com.ctshk.rpc.system.req.*;
import com.ctshk.rpc.system.req.main.data.MainDataDeductionRulesIdReq;
import com.ctshk.rpc.system.service.*;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 团期 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-01-20
 */
@DubboService
public class CustomizedTripScheduleServiceImpl extends ServiceImpl<CustomizedTripScheduleMapper, CustomizedTripSchedule> implements ICustomizedTripScheduleService {

    @Autowired
    private CustomizedTripScheduleMapper tripScheduleMapper;
    @Autowired
    private CustomizedTripScheduleAdvancedMapper tripScheduleAdvancedMapper;
    @Autowired
    private CustomizedTripScheduleInsuranceMapper tripScheduleInsuranceMapper;
    @Autowired
    private CustomizedTripScheduleInfoChangeRuleMapper tripScheduleInfoChangeRuleMapper;
    @Autowired
    private CustomizedTripScheduleVisaMapper tripScheduleVisaMapper;
    @Autowired
    private VisaFreeCountriesMapper visaFreeCountriesMapper;
    @Autowired
    private CustomizedTripScheduleFreeQuotePackageMapper tripScheduleFreeQuotePackageMapper;
    @Autowired
    private CustomizedTripSchedulePackageServiceItemsMapper tripSchedulePackageServiceItemsMapper;
    @Autowired
    private CustomizedTripScheduleQuoteServiceItemsMapper tripScheduleQuoteServiceItemsMapper;
    @Autowired
    private CustomizedTripScheduleTouristPriceMapper tripScheduleTouristPriceMapper;
    @Autowired
    private CustomizedTripScheduleDateMapper tripScheduleDateMapper;
    @Autowired
    private CustomizedQuotationServiceImpl quotationServiceImpl;
    @Autowired
    private CustomizedTripScheduleCollectionFeeMapper tripScheduleCollectionFeeMapper;
    @Autowired
    private CustomizedTripScheduleCollectionTouristFeeMapper tripScheduleCollectionTouristFeeMapper;
    @Autowired
    private CustomizedTripScheduleFeeAdjustMapper tripScheduleFeeAdjustMapper;
    @Autowired
    private CustomizedInquiryMapper inquiryMapper;
    @Autowired
    private CustomizedQuotationMapper quotationMapper;
    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private ISysAreaService areaService;
    @DubboReference
    private IMainDataTourGroupCodeService tourGroupCodeService;
    /*@DubboReference
    private IMainDataTourGroupService groupService;*/

    @DubboReference
    private ISysBigClientService bigClientService;
    @DubboReference
    private ISysPermissionService sysPermissionService;
    @DubboReference
    private IMainDataCollectionPlaceService mainDataCollectionPlaceService;
    @DubboReference
    private IInsuranceService insuranceService;
    @DubboReference
    private ISysApprovalService sysApprovalService;
    @DubboReference
    private IMainDataCurrencyService mainDataCurrencyService;

    @Autowired
    private VisaMapper visaMapper;

    @Autowired
    CustomizedQuotationFreeQuoteServiceItemsMapper freeQuoteServiceItemsMapper;
    @Autowired
    CustomizedTripScheduleItineraryMapper tripScheduleItineraryMapper;
    @Autowired
    CustomizedTripScheduleItineraryDayMapper tripScheduleItineraryDayMapper;
    @Autowired
    CustomizedQuotationTouristTypeMapper quotationTouristTypeMapper;
    @Autowired
    private CustomizedTripScheduleChannelMapper tripScheduleChannelMapper;
    @Autowired
    private CustomizedTripScheduleChannelDetailMapper tripScheduleChannelDetailMapper;
    @Autowired
    private CustomizedTripScheduleTouristCountMapper tripScheduleTouristCountMapper;
    @Autowired
    private CustomizedTripScheduleAmountStatisticsMapper tripScheduleAmountStatisticsMapper;


    @DubboReference
    IMainDataFieldDataService mainDataFieldDataService;
    @DubboReference
    private IMainDataTripInfoChangeRuleService tripInfoChangeRuleService;
    @DubboReference
    private IMainDataDeductionRulesService dataDeductionRulesService;
    @DubboReference
    private ICustomizedTripScheduleTouristCountService tripScheduleTouristCountService;
    @DubboReference
    private ITeaPartyService teaPartyService;
    @DubboReference
    private IGroupDistributionService groupDistributionService;
    @DubboReference
    private ICustomizedOrderTouristRefundService customizedOrderTouristRefundService;


    /**
     * 团期列表
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    public PageResponse<TripScheduleListDTO> list(TripScheduleListReq req, TokenUser currentUser) {
        /*if (req.getDepartType() == null){
            req.setDepartType(3);
        }*/
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), currentUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        QueryWrapper<CustomizedTripSchedule> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(req.getTripInfo()), "trip_number", req.getTripInfo());
        wrapper.or();
        wrapper.like(StringUtils.isNotBlank(req.getTripInfo()), "name", req.getTripInfo());
    //    wrapper.eq("depart_type",req.getDepartType());
        wrapper.eq(req.getGroupStatus() != null && req.getGroupStatus().intValue() > 0, "group_status", req.getGroupStatus());
        wrapper.eq(req.getDeparturePlaceId() != null, "departure_place_id", req.getDeparturePlaceId());
        wrapper.eq(req.getDestinationId() != null, "destination_id", req.getDestinationId());
        wrapper.eq(req.getChargePersonId() != null, "charge_person_id", req.getChargePersonId());
        wrapper.eq(req.getOpId() != null, "op_id", req.getOpId());
        wrapper.eq(req.getTravelDays() != null && req.getTravelDays().intValue() > 0, "travel_days", req.getTravelDays());
        wrapper.lambda().in(!GlobalConstants.Role.isAdmin(currentUser.getUsername()), CustomizedTripSchedule::getCreateId, permissionResult.getData());
        if (req.getBeginDate() != null) {
            LocalDateTime endDate = LocalDateTime.now();
            LocalDateTime beginDate = DateUtil.parse(req.getBeginDate() + " 00:00:00");
            if (req.getEndDate() != null) {
                endDate = DateUtil.parse(req.getEndDate() + " 00:00:00");
            }
            wrapper.between("departure_date", beginDate, endDate);
        }
        wrapper.eq("create_id", currentUser.getId());
        wrapper.orderByDesc("gmt_create");
        Page<CustomizedTripSchedule> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        iPage = tripScheduleMapper.selectPage(iPage, wrapper);
        List<TripScheduleListDTO> listDtoList = new ArrayList<>();
        iPage.getRecords().forEach(tripSchedule -> {
            TripScheduleListDTO tripScheduleListDTO = EntityUtil.copy(tripSchedule, TripScheduleListDTO.class);
            tripScheduleListDTO.setId(tripSchedule.getId());
            tripScheduleListDTO.setDepartureDateWeekDay(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
            try {
                if (tripSchedule.getOpId() != null) {
                    UserDTO opUser = sysUserService.queryCacheUser(tripSchedule.getOpId());
                    if (opUser != null) {
                        tripScheduleListDTO.setOpDept(opUser.getDept());
                    }
                }
                if (tripSchedule.getChargePersonId() != null) {
                    UserDTO chargeUser = sysUserService.queryCacheUser(tripSchedule.getChargePersonId());
                    if (chargeUser != null) {
                        tripScheduleListDTO.setChargePersonDept(chargeUser.getDept());
                    }
                }
                QueryWrapper<CustomizedTripScheduleAmountStatistics> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("schedule_id", tripSchedule.getId());
                queryWrapper.eq("is_deleted", 0);
                CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.selectOne(queryWrapper);
                if (amountStatistics != null) {
                    tripScheduleListDTO.setTotalAmount(amountStatistics.getTotalFee());
                    tripScheduleListDTO.setTotalPeople(amountStatistics.getTotalPeople());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
            listDtoList.add(tripScheduleListDTO);
        });
        PageResponse<TripScheduleListDTO> result = new PageResponse<>(listDtoList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        return result;
    }

    /**
     * 开团基本资料
     *
     * @param req
     * @return
     */
    @Override
    public Result<TripScheduleBaseInfoDTO> tripScheduleBaseInfo(TripScheduleInfoReq req) {
        TripScheduleBaseInfoDTO dto = null;
        if (req.getScheduleId() == null) {
            if (StringUtils.isBlank(req.getInquiryInfo())) {
                return Result.success(null);
            }
            QueryWrapper<CustomizedInquiry> inquiryWrapper = new QueryWrapper<>();
            inquiryWrapper.like("inquiry_number", req.getInquiryInfo());
            inquiryWrapper.or();
            inquiryWrapper.like("inquiry_title", req.getInquiryInfo());
            inquiryWrapper.eq("is_deleted", 0);
            CustomizedInquiry inquiry = inquiryMapper.selectOne(inquiryWrapper);
            if (inquiry == null) {
                return Result.success(null);
            }
            //封装团期基本信息
            dto = packTripScheduleBaseInfoDTOByInquiry(inquiry);
        } else {
            CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
            //获取团期基本信息
            dto = getTripScheduleBaseInfo(tripSchedule);
        }
        return Result.success(dto);
    }

    /**
     * 团期销售设置信息
     *
     * @param req
     * @return
     */
    @Override
    public Result<TripScheduleSalesSettingInfoDTO> salesSettingInfo(TripScheduleIdReq req) {
        try {
            TripScheduleSalesSettingInfoDTO dto = getTripScheduleSalesSettingByTripSchedule(req.getTripScheduleId());
            return Result.success(dto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.failed(new BusinessException(SystemError.SYS_500));
    }

    /**
     * 根据报价单获取团期销售设置信息
     *
     * @param req
     * @return
     */
    @Override
    public Result<SalesSettingPackageInfoDTO> salesSettingInfoByQuotation(TripScheduleSalesSettingInfoReq req) {
        try {
            SalesSettingPackageInfoDTO dto = getTripScheduleSalesSettingByQuatation(req.getQuotationInfo());
            return Result.success(dto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.failed(new BusinessException(SystemError.SYS_500));
    }

    /**
     * 团期列表(预订中心)
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    public PageResponse<TripScheduleListDTO> customizedCenterList(TripScheduleCustomizedCenterListReq req, TokenUser currentUser) {
        /*if (req.getDepartType() == null){
            req.setDepartType(3);
        }*/
        try {
            Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), currentUser.getId());
            if (!permissionResult.isSuccess()) {
                SystemError result = SystemError.getDefined(permissionResult.getCode());
                throw new BusinessException(result);
            }
            req.setPermissionList(permissionResult.getData());
            List<TripScheduleListDTO> tripScheduleListDTOList = new ArrayList<>();
            IPage<CustomizedTripSchedule> iPage = new Page<>(req.getPageNo(), req.getPageSize());
            //出行天数
            if (req.getTravelDays() != null && req.getTravelDays().size() > 0) {
                //天数list
                List list = new ArrayList();
                String travelDays = null;
                req.setOverTen(false);
                if (req.getTravelDays().size() == NumberConstant.ONE.getValue()) {
                    //单选
                    if (StrConstant.NINETYNINE.getValue().equals(req.getTravelDays().get(0).toString())) {
                        //10天以上
                        //    travelDays = NumberConstant.TEN.getValue().toString();
                        req.setOverTen(true);
                    } else if (!req.getTravelDays().get(0).toString().contains(",")) {
                        //非10天以上 = 1天
                        travelDays = NumberConstant.ONE.getValue().toString();
                        list.add(travelDays);
                    } else {
                        //多个天数
                        travelDays = req.getTravelDays().get(0).toString();
                        String[] split = travelDays.split(",");
                        for (String s : split) {
                            list.add(s);
                        }
                    }
                } else {
                    //多选
                    req.getTravelDays().forEach(str -> {
                        if (str.toString().contains(",")) {
                            //多个天数
                            String[] split = str.toString().split(",");
                            for (String s : split) {
                                list.add(s);
                            }
                        } else {
                            //单个天数
                            list.add(str);
                        }
                    });
                }
                req.setList(list);
            }
            UserDTO userDTO = sysUserService.queryCacheUser(currentUser.getId());
            if (userDTO == null) {
                throw new BusinessException(SystemError.SYS_420);
            }
            //当前用户可查看团期ID列表
            List<Long> idList = tripScheduleChannelDetailMapper.queryScheduleListByUser(userDTO.getId(), userDTO.getDeptId());
            if (CollectionUtils.isNotEmpty(idList)) {
                req.setIdList(idList);
            }
            Page<CustomizedTripSchedule> page = tripScheduleMapper.customizedCenterList(req, iPage);
            if (CollectionUtils.isEmpty(page.getRecords())) {
                return PageResponse.empty(page.getCurrent());
            }
            page.getRecords().forEach(tripSchedule -> {
                TripScheduleListDTO tripScheduleListDTO = EntityUtil.copy(tripSchedule, TripScheduleListDTO.class);
                tripScheduleListDTO.setId(tripSchedule.getId());
                //星期几
                tripScheduleListDTO.setDepartureDateWeekDay(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
                //查部门
                if (tripSchedule.getOpId() != null) {
                    UserDTO opUser = sysUserService.queryCacheUser(tripSchedule.getOpId());
                    if (opUser != null) {
                        tripScheduleListDTO.setOpDept(opUser.getDept());
                    }
                }
                if (tripSchedule.getChargePersonId() != null) {
                    UserDTO chargeUser = sysUserService.queryCacheUser(tripSchedule.getChargePersonId());
                    if (chargeUser != null) {
                        tripScheduleListDTO.setChargePersonDept(chargeUser.getDept());
                    }
                }
                //金额人数统计
                QueryWrapper<CustomizedTripScheduleAmountStatistics> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("schedule_id", tripSchedule.getId());
                queryWrapper.eq("is_deleted", 0);
                CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.selectOne(queryWrapper);
                if (amountStatistics != null) {
                    tripScheduleListDTO.setTotalPeople(amountStatistics.getTotalPeople());
                    tripScheduleListDTO.setTotalAmount(amountStatistics.getTotalFee());
                }
                //销售
                if (tripSchedule.getInquiryId() != null) {
                    CustomizedInquiry inquiry = inquiryMapper.selectById(tripSchedule.getInquiryId());
                    if (inquiry != null && Objects.equals(inquiry.getIsDeleted(), 0)) {
                        tripScheduleListDTO.setSaleUserName(inquiry.getSalespersonName());
                        UserDTO userDTO1 = sysUserService.queryCacheUser(inquiry.getSalespersonId());
                        if (userDTO1 != null) {
                            tripScheduleListDTO.setSaleUserDept(userDTO1.getDept());
                        }
                    }
                } else if (tripSchedule.getQuotationId() != null) {
                    CustomizedQuotation quotation = quotationMapper.selectById(tripSchedule.getQuotationId());
                    if (quotation != null && Objects.equals(quotation.getIsDeleted(), 0)) {
                        if (quotation.getInquiryId() != null) {
                            CustomizedInquiry inquiry = inquiryMapper.selectById(quotation.getInquiryId());
                            if (inquiry != null && Objects.equals(inquiry.getIsDeleted(), 0)) {
                                tripScheduleListDTO.setSaleUserName(inquiry.getSalespersonName());
                                UserDTO userDTO1 = sysUserService.queryCacheUser(inquiry.getSalespersonId());
                                if (userDTO1 != null) {
                                    tripScheduleListDTO.setSaleUserDept(userDTO1.getDept());
                                }
                            }
                        }
                    }
                }
                tripScheduleListDTOList.add(tripScheduleListDTO);
            });
            PageResponse<TripScheduleListDTO> result = new PageResponse<>(tripScheduleListDTOList, page.getCurrent() == 1,
                    page.getTotal() <= (page.getCurrent() * page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
            System.out.println("团期列表 => 返回数据 ===>>> " + result.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过id获取团期（内部接口）
     *
     * @param scheduleId
     * @return
     */
    @Override
    public CustomizedTripScheduleDTO queryByScheduleId(Long scheduleId) {
        if (scheduleId == null) {
            return null;
        }
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(scheduleId);
        if (tripSchedule == null) {
            return null;
        }
        CustomizedTripScheduleDTO tripScheduleDTO = EntityUtil.copy(tripSchedule, CustomizedTripScheduleDTO.class);
        //高级设置
        QueryWrapper<CustomizedTripScheduleAdvanced> advancedWrapper = new QueryWrapper<>();
        advancedWrapper.eq("schedule_id", scheduleId);
        advancedWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleAdvanced advanced = tripScheduleAdvancedMapper.selectOne(advancedWrapper);
        if (advanced != null) {
            TripScheduleAdvancedDTO advancedDTO = getTripScheduleAdvanced(advanced, scheduleId);
            tripScheduleDTO.setAdvancedDTO(advancedDTO);
        }
        if (tripScheduleDTO.getQuotationType().intValue() == NumberConstant.TWO.getValue()) {
            //行程报价
            BigDecimal sumSinglePrice = tripScheduleDateMapper.sumSinglePrice(scheduleId);
            if (sumSinglePrice != null) {
                tripScheduleDTO.setQuoteTotalSinglePrice(sumSinglePrice);
            }
        }
        //代收费用旅客单价
        List<CollectionTouristPriceDTO> collectionTouristList = tripScheduleCollectionTouristFeeMapper.getCollectionPriceByTourist(scheduleId);
        if (collectionTouristList != null && collectionTouristList.size() > 0) {
            for (CollectionTouristPriceDTO touristPriceDTO : collectionTouristList) {
                //旅客类型代收费用列表
                List<TouristCollectionItemDTO> collectionItemList = tripScheduleCollectionTouristFeeMapper.sumCollectionItemList(touristPriceDTO.getTouristTypeId(), scheduleId);
                if (CollectionUtils.isNotEmpty(collectionItemList)) {
                    BigDecimal price = BigDecimal.ZERO;
                    for (TouristCollectionItemDTO itemDTO : collectionItemList) {
                        price = price.add(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()));
                    }
                    touristPriceDTO.setPrice(price);
                    touristPriceDTO.setCollectionItemList(collectionItemList);
                }
            }
            tripScheduleDTO.setCollectionTouristList(collectionTouristList);
        }
        //行程信息
        QueryWrapper<CustomizedTripScheduleItinerary> itineraryWrapper = new QueryWrapper<>();
        itineraryWrapper.eq("schedule_id", scheduleId);
        itineraryWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleItinerary itinerary = tripScheduleItineraryMapper.selectOne(itineraryWrapper);
        if (itinerary != null) {
            tripScheduleDTO.setTourFeeInclude(itinerary.getTourFeeInclude());
            tripScheduleDTO.setTourFeeExclude(itinerary.getTourFeeExclude());
            tripScheduleDTO.setSignNotice(itinerary.getSignNotice());
            tripScheduleDTO.setRemark(itinerary.getRemark());
        }
        //调整费用
        QueryWrapper<CustomizedTripScheduleFeeAdjust> feeAdjustQueryWrapper = new QueryWrapper<>();
        feeAdjustQueryWrapper.eq("schedule_id", scheduleId);
        feeAdjustQueryWrapper.eq("is_deleted", 0);
        List<CustomizedTripScheduleFeeAdjust> feeAdjustList = tripScheduleFeeAdjustMapper.selectList(feeAdjustQueryWrapper);
        if (feeAdjustList != null && feeAdjustList.size() > 0) {
            List<TripScheduleFeeAdjustDTO> feeAdjustDTOList = new ArrayList<>();
            feeAdjustList.forEach(feeAdjust -> {
                TripScheduleFeeAdjustDTO feeAdjustDTO = EntityUtil.copy(feeAdjust, TripScheduleFeeAdjustDTO.class);
                feeAdjustDTOList.add(feeAdjustDTO);
            });
            tripScheduleDTO.setFeeAdjustList(feeAdjustDTOList);
        }
        return tripScheduleDTO;
    }

    /**
     * 查询指定id集团期(内部接口)
     *
     * @param req
     * @return
     */
    @Override
    public List<TripScheduleListDTO> getTripScheduleList(TripScheduleListIdReq req) {
        List<CustomizedTripSchedule> list = tripScheduleMapper.selectBatchIds(req.getListId());
        if (list != null && list.size() > 0) {
            List<TripScheduleListDTO> dtoList = new ArrayList<>();
            list.forEach(tripSchedule -> {
                TripScheduleListDTO dto = EntityUtil.copy(tripSchedule, TripScheduleListDTO.class);
                dtoList.add(dto);
            });
            return dtoList;
        }
        return null;
    }


    /**
     * 保存团期基本信息
     *
     * @param req
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveTripScheduleBaseInfo(SaveTripScheduleBaseInfoReq req, TokenUser user) {
        System.out.println(" 保存团期基本信息 => 请求参数 req ===>>> " + req.toString());
        if (req.getDepartType() == null){
            req.setDepartType(3);
        }
        CustomizedTripSchedule tripSchedule = new CustomizedTripSchedule();
        //操作类型。1 新增,2 修改
        int operateType = NumberConstant.ONE.getValue();
        if (req.getId() != null) {
            CustomizedTripSchedule schedule = tripScheduleMapper.selectById(req.getId());
            if (schedule == null) {
                throw new BusinessException(SystemError.CUSTOM_3006);
            }
            tripSchedule = schedule;
            operateType = NumberConstant.TWO.getValue();
        }
        //封装团期属性
        tripSchedule = setTripScheduleAttr(req, tripSchedule);
        int result = 0;
        if (operateType == NumberConstant.ONE.getValue()) {
            //新增
            //设置团期属性
            tripSchedule = saveTripScheduleAttr(tripSchedule, req, user.getId());
            result = tripScheduleMapper.insert(tripSchedule);
        } else {
            //修改
            tripSchedule.setModifiedId(user.getId());
            result = tripScheduleMapper.updateById(tripSchedule);
        }
        if (result <= 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        //处理保险
        dealTripScheduleInsurance(req, tripSchedule.getId(), user.getId());
        //处理签证
        dealTripScheduleVisa(req, tripSchedule.getId(), user.getId());
        //处理团队高级设置
        dealTripScheduleAdvanced(req, tripSchedule.getId(), user.getId(), operateType);
        return Result.success(tripSchedule.getId());
    }


    /**
     * 保存团期销售设置
     *
     * @param req
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveTripScheduleSalesSetting(SaveTripScheduleSalesSettingReq req, TokenUser user) {
        //查询团期
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        if (StringUtils.isNotBlank(req.getQuotationNumber())) {
            QueryWrapper<CustomizedQuotation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("quotation_number", req.getQuotationNumber());
            queryWrapper.eq("is_deleted", 0);
            CustomizedQuotation quotation = quotationMapper.selectOne(queryWrapper);
            if (quotation != null) {
                tripSchedule.setQuotationId(quotation.getId());
                tripSchedule.setQuotationTitle(quotation.getQuotationTitle());
                tripSchedule.setQuotationNumber(quotation.getQuotationNumber());
                if (quotation.getInquiryId() != null) {
                    CustomizedInquiry inquiry = inquiryMapper.selectById(quotation.getInquiryId());
                    if (inquiry != null) {
                        tripSchedule.setInquiryId(quotation.getInquiryId());
                        tripSchedule.setInquiryNumber(inquiry.getInquiryNumber());
                        tripSchedule.setInquiryTitle(inquiry.getInquiryTitle());
                    }
                }
            }
        }
        //团期是否改动
        boolean isChange = false;
        if (req.getDeliveryDays() != null) {
            tripSchedule.setDeliveryDays(req.getDeliveryDays());
            isChange = true;
        }
        if (req.getMinDeposit() != null) {
            tripSchedule.setMinDeposit(req.getMinDeposit());
            isChange = true;
        }
        if (tripSchedule.getQuotationType() != null) {
            if (tripSchedule.getQuotationType().intValue() != req.getQuotationType().intValue()) {
                tripSchedule.setQuotationType(req.getQuotationType());
                isChange = true;
            }
        } else {
            tripSchedule.setQuotationType(req.getQuotationType());
            isChange = true;
        }
        if (req.getQuotationType().intValue() == NumberConstant.ONE.getValue()) {
            //自由报价
            if (req.getGroupFeeType() != null) {
                if (tripSchedule.getGroupFeeType() == null) {
                    isChange = true;
                    tripSchedule.setGroupFeeType(req.getGroupFeeType());
                } else {
                    if (tripSchedule.getGroupFeeType().intValue() != req.getGroupFeeType().intValue()) {
                        isChange = true;
                        tripSchedule.setGroupFeeType(req.getGroupFeeType());
                    }
                }
            }
        }
        if (isChange) {
            tripSchedule.setModifiedId(user.getId());
            int update = tripScheduleMapper.updateById(tripSchedule);
            if (update < 0) {
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //保存套餐信息
        saveTripSchedulePackage(req, user.getId());
        //保存代收费用
        saveTripScheduleCollectionFee(req, user.getId());
        //保存增減團費設置
        saveTripScheduleFeeAdjust(req, user.getId());
        //保存线下渠道信息
        saveTripScheduleChannel(req, user.getId());
        return Result.success(req.getScheduleId());
    }

    /**
     * 保存线下渠道信息
     *
     * @param req
     * @param userId
     */
    private void saveTripScheduleChannel(SaveTripScheduleSalesSettingReq req, Long userId) {
        QueryWrapper<CustomizedTripScheduleChannel> channelWrapper = new QueryWrapper<>();
        channelWrapper.eq("schedule_id", req.getScheduleId());
        channelWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleChannel channel = tripScheduleChannelMapper.selectOne(channelWrapper);
        int operate = 0;
        if (channel == null) {
            //新增
            channel = new CustomizedTripScheduleChannel();
            channel.setId(SnowflakeIdWorker.nextId());
            channel.setScheduleId(req.getScheduleId());
            channel.setVisableType(req.getVisableType());
            channel.setCreateId(userId);
            channel.setIsDeleted(0);
            operate = tripScheduleChannelMapper.insert(channel);
        } else {
            //修改
            channel.setModifiedId(userId);
            if (channel.getVisableType().intValue() == 3) {
                //清空明细
                tripScheduleChannelDetailMapper.cleanByRelationId(channel.getId(), userId);
            }
            channel.setVisableType(req.getVisableType());
            operate = tripScheduleChannelMapper.updateById(channel);
        }
        if (operate == 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        if (req.getVisableType().intValue() == 2) {
            List<TripScheduleChannelDetailDTO> detailDTOList = req.getDetailList();
            if (detailDTOList == null || detailDTOList.size() == 0) {
                throw new BusinessException(SystemError.CUSTOM_3010);
            }
            for (TripScheduleChannelDetailDTO detailDTO : detailDTOList) {
                channel.setAdjustType(detailDTO.getAdjustType());
                channel.setAmount(detailDTO.getAmount());
                channel.setPercent(detailDTO.getPercent());
            }
            int update = tripScheduleChannelMapper.updateById(channel);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_408);
            }
        }else if (req.getVisableType().intValue() == 3) {
            //新增明细
            List<CustomizedTripScheduleChannelDetail> detailList = new ArrayList<>();
            List<TripScheduleChannelDetailDTO> detailDTOList = req.getDetailList();
            if (detailDTOList == null || detailDTOList.size() == 0) {
                throw new BusinessException(SystemError.CUSTOM_3010);
            }
            for (TripScheduleChannelDetailDTO detailDTO : detailDTOList) {
                CustomizedTripScheduleChannelDetail detail = EntityUtil.copy(detailDTO, CustomizedTripScheduleChannelDetail.class);
                detail.setId(SnowflakeIdWorker.nextId());
                //勾选类型。1：部门，2：员工
                if (Objects.equals(detailDTO.getCheckType(), 1)) {
                    UserDTO userDTO = sysUserService.queryCacheUser(userId);
                    if (userDTO != null) {
                        detail.setRelationId(userDTO.getDeptId());
                    }
                } else {
                    detail.setRelationId(userId);
                }
                detail.setChannelId(channel.getId());
                detail.setCreateId(userId);
                detail.setIsDeleted(0);
                detailList.add(detail);
            }
            Integer batch = tripScheduleChannelDetailMapper.insertBatchSomeColumn(detailList);
            if (batch < detailList.size()) {
                throw new BusinessException(SystemError.SYS_437);
            }
        }
    }

    /**
     * 团期行程信息
     *
     * @param req
     * @return
     */
    @Override
    public Result<TripScheduleItineraryDTO> tripInfo(TripScheduleIdReq req) {
        try {
            TripScheduleItineraryDTO itineraryDTO = new TripScheduleItineraryDTO();
            //查询团期行程信息
            QueryWrapper<CustomizedTripScheduleItinerary> itineraryWrapper = new QueryWrapper<>();
            itineraryWrapper.eq("schedule_id", req.getTripScheduleId());
            itineraryWrapper.eq("is_deleted", 0);
            CustomizedTripScheduleItinerary itinerary = tripScheduleItineraryMapper.selectOne(itineraryWrapper);
            if (itinerary != null) {
                itineraryDTO = EntityUtil.copy(itinerary, TripScheduleItineraryDTO.class);
                if (Objects.equals(itinerary.getItineraryType(), 2)) {
                    List<TripScheduleItineraryDayDTO> itineraryDayList = new ArrayList<>();
                    CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getTripScheduleId());
                    Integer travelDays = tripSchedule.getTravelDays();
                    if (travelDays > 0) {
                        //构造空数组给前端
                        for (int i = 0; i < travelDays; i++) {
                            TripScheduleItineraryDayDTO dayDTO = new TripScheduleItineraryDayDTO();
                            itineraryDayList.add(dayDTO);
                        }
                        itineraryDTO.setItineraryDayList(itineraryDayList);
                        return Result.success(itineraryDTO);
                    }
                }
                if (StringUtils.isNotBlank(itinerary.getSelfFeeJson())) {
                    List<SelfFeeJson> selfFeeJsonList = JSON.parseArray(itinerary.getSelfFeeJson(), SelfFeeJson.class);
                    itineraryDTO.setSelfFeeJsonList(selfFeeJsonList);
                }
                itineraryDTO.setId(itinerary.getId());
                //团期行程每日介绍
                List<TripScheduleItineraryDayDTO> itineraryDayList = tripScheduleItineraryDayMapper.queryList(itinerary.getId());
                if (itineraryDayList != null && itineraryDayList.size() > 0) {
                    itineraryDayList.forEach(itineraryDay -> {
                        if (StringUtils.isNotBlank(itineraryDay.getFoodJsonStr())) {
                            FoodJson foodJson = JSON.parseObject(itineraryDay.getFoodJsonStr(), FoodJson.class);
                            if (foodJson != null) {
                                itineraryDay.setFoodBreakfast(foodJson.getFoodBreakfast());
                                itineraryDay.setFoodLunch(foodJson.getFoodLunch());
                                itineraryDay.setFoodSupper(foodJson.getFoodSupper());
                                itineraryDay.setFoodPhotoJson(foodJson.getFoodPhotoJson());
                                if (CollectionUtils.isNotEmpty(foodJson.getFoodJson())) {
                                    itineraryDay.setFoodJson(foodJson.getFoodJson());
                                }
                            }
                        }
                        if (StringUtils.isNotBlank(itineraryDay.getScenicJsonStr())) {
                            List<ScenicJson> scenicJson = JSON.parseArray(itineraryDay.getScenicJsonStr(), ScenicJson.class);
                            itineraryDay.setScenicJson(scenicJson);
                        }
                        if (StringUtils.isNotBlank(itineraryDay.getHotelJsonStr())) {
                            List<HotelJson> hotelJson = JSON.parseArray(itineraryDay.getHotelJsonStr(), HotelJson.class);
                            itineraryDay.setHotelJson(hotelJson);
                        }
                        if (StringUtils.isNotBlank(itineraryDay.getTrafficJsonStr())) {
                            List<TrafficJson> trafficJson = JSON.parseArray(itineraryDay.getTrafficJsonStr(), TrafficJson.class);
                            itineraryDay.setTrafficJson(trafficJson);
                        }
                    });
                    itineraryDTO.setItineraryDayList(itineraryDayList);
                } else {
                    CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getTripScheduleId());
                    Integer travelDays = tripSchedule.getTravelDays();
                    if (travelDays > 0) {
                        //构造空数组给前端
                        for (int i = 0; i < travelDays; i++) {
                            TripScheduleItineraryDayDTO dayDTO = new TripScheduleItineraryDayDTO();
                            itineraryDayList.add(dayDTO);
                        }
                        itineraryDTO.setItineraryDayList(itineraryDayList);
                        return Result.success(itineraryDTO);
                    }
                }
                return Result.success(itineraryDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(null);
    }

    /**
     * 保存团期行程信息
     *
     * @param req
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveItineraryInfo(SeriesTripScheduleItineraryDayReq req, TokenUser user) {
        System.out.println(" 保存团期行程信息 => 请求参数 ===>>> " + req.toString());
        try {
            CustomizedTripScheduleItinerary itinerary = EntityUtil.copy(req, CustomizedTripScheduleItinerary.class);
            //操作类型。1 新增，2 修改
            int operateType = NumberConstant.ONE.getValue();
            if (req.getId() != null) {
                QueryWrapper<CustomizedTripScheduleItinerary> itineraryWrapper = new QueryWrapper<>();
                itineraryWrapper.eq("schedule_id", req.getId());
                itineraryWrapper.eq("is_deleted", 0);
                CustomizedTripScheduleItinerary tripScheduleItinerary = tripScheduleItineraryMapper.selectOne(itineraryWrapper);
                if (tripScheduleItinerary != null) {
                    operateType = NumberConstant.TWO.getValue();
                    itinerary.setId(tripScheduleItinerary.getId());
                }
            }
            //补充信息
            SupplementInfoReq supplementInfoReq = req.getSupplementInfoReq();
            if (supplementInfoReq != null) {
                itinerary.setRemark(supplementInfoReq.getRemark());
                if (StringUtils.isNotBlank(supplementInfoReq.getTourFeeInclude())) {
                    itinerary.setTourFeeInclude(supplementInfoReq.getTourFeeInclude());
                }
                if (StringUtils.isNotBlank(supplementInfoReq.getTourFeeExclude())) {
                    itinerary.setTourFeeExclude(supplementInfoReq.getTourFeeExclude());
                }
                if (supplementInfoReq.getSelfFeeJsonList() != null) {
                    Gson gson = new Gson();
                    String json = gson.toJson(supplementInfoReq.getSelfFeeJsonList());
                    itinerary.setSelfFeeJson(json);
                }
                if (StringUtils.isNotBlank(supplementInfoReq.getSelfFeeRemark())) {
                    itinerary.setSelfFeeRemark(supplementInfoReq.getSelfFeeRemark());
                }
                if (StringUtils.isNotBlank(supplementInfoReq.getSignNotice())) {
                    itinerary.setSignNotice(supplementInfoReq.getSignNotice());
                }
                if (StringUtils.isNotBlank(supplementInfoReq.getRemark())) {
                    itinerary.setRemark(supplementInfoReq.getRemark());
                }
            }
            if (req.getItineraryType().intValue() == NumberConstant.ONE.getValue()) {
                //标准行程
                List<SeriesTripItineraryDayReq> list = req.getList();
                if (operateType == NumberConstant.ONE.getValue()) {
                    //新增
                    itinerary.setId(SnowflakeIdWorker.nextId());
                    itinerary.setScheduleId(req.getId());
                    itinerary.setCreateId(user.getId());
                    itinerary.setGmtCreate(LocalDateTime.now());
                    itinerary.setIsDeleted(0);
                    int save = tripScheduleItineraryMapper.insert(itinerary);
                    if (save <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                } else {
                    //修改
                    itinerary.setModifiedId(user.getId());
                    int update = tripScheduleItineraryMapper.updateById(itinerary);
                    if (update > 0) {
                        if (list != null && list.size() > 0) {
                            //清空行程每日介绍
                            tripScheduleItineraryDayMapper.clearByItinerary(itinerary.getId(), user.getId());
                        }
                    }
                }
                if (list != null && list.size() > 0) {
                    //新增行程每日介绍
                    List<CustomizedTripScheduleItineraryDay> itineraryDayList = new ArrayList<>();
                    for (SeriesTripItineraryDayReq itineraryDayReq : list) {
                        CustomizedTripScheduleItineraryDay itineraryDay = EntityUtil.copy(itineraryDayReq, CustomizedTripScheduleItineraryDay.class);
                        itineraryDay.setId(SnowflakeIdWorker.nextId());
                        itineraryDay.setItineraryId(itinerary.getId());
                        itineraryDay.setScheduleId(itinerary.getScheduleId());
                        if (StringUtils.isNotBlank(itineraryDayReq.getFoodBreakfast()) || StringUtils.isNotBlank(itineraryDayReq.getFoodLunch()) || StringUtils.isNotBlank(itineraryDayReq.getFoodSupper()) || itineraryDayReq.getFoodPhotoJson() != null) {
                            FoodJson foodJson = new FoodJson();
                            foodJson.setFoodLunch(itineraryDayReq.getFoodLunch());
                            foodJson.setFoodBreakfast(itineraryDayReq.getFoodBreakfast());
                            foodJson.setFoodSupper(itineraryDayReq.getFoodSupper());
                            foodJson.setFoodPhotoJson(itineraryDayReq.getFoodPhotoJson());
                            if (CollectionUtils.isNotEmpty(itineraryDayReq.getFoodJson())) {
                                foodJson.setFoodJson(itineraryDayReq.getFoodJson());
                            }
                            Gson gson = new Gson();
                            String json = gson.toJson(foodJson);
                            itineraryDay.setFoodJson(json);
                        }
                        if (itineraryDayReq.getHotelJson() != null) {
                            Gson gson = new Gson();
                            String json = gson.toJson(itineraryDayReq.getHotelJson());
                            itineraryDay.setHotelJson(json);
                        }
                        if (itineraryDayReq.getTrafficJson() != null) {
                            Gson gson = new Gson();
                            String json = gson.toJson(itineraryDayReq.getTrafficJson());
                            itineraryDay.setTrafficJson(json);
                        }
                        if (itineraryDayReq.getScenicJson() != null) {
                            Gson gson = new Gson();
                            String json = gson.toJson(itineraryDayReq.getScenicJson());
                            itineraryDay.setScenicJson(json);
                        }
                        itineraryDay.setCreateId(user.getId());
                        itineraryDay.setGmtCreate(LocalDateTime.now());
                        itineraryDay.setIsDeleted(0);
                        itineraryDayList.add(itineraryDay);
                    }
                    Integer batch = tripScheduleItineraryDayMapper.insertBatchSomeColumn(itineraryDayList);
                    if (batch < itineraryDayList.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            } else {
                //簡易行程
                if (req.getSimpleJourneyReq() != null) {
                    itinerary.setSimpleItinerary(req.getSimpleJourneyReq().getSimpleItinerary());
                }
                if (operateType == NumberConstant.ONE.getValue()) {
                    //新增
                    itinerary.setId(SnowflakeIdWorker.nextId());
                    itinerary.setScheduleId(req.getId());
                    itinerary.setCreateId(user.getId());
                    itinerary.setGmtCreate(LocalDateTime.now());
                    itinerary.setIsDeleted(0);
                    int save = tripScheduleItineraryMapper.insert(itinerary);
                    if (save <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                } else {
                    //修改
                    itinerary.setModifiedId(user.getId());
                    int update = tripScheduleItineraryMapper.updateById(itinerary);
                    if (update <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
            //开团
            CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getId());
            if (tripSchedule == null) {
                throw new BusinessException(SystemError.CUSTOM_3006);
            }
            if (operateType == NumberConstant.ONE.getValue()) {
                //新增
                tripSchedule.setGroupStatus(1);
                tripSchedule.setModifiedId(user.getId());
                int update = tripScheduleMapper.updateById(tripSchedule);
                if (update <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }

            if (tripSchedule.getInquiryId() != null) {
                CustomizedInquiry inquiry = inquiryMapper.selectById(tripSchedule.getInquiryId());
                if (Objects.equals(inquiry.getIsDeleted(), 0) && !Objects.equals(inquiry.getInquiryStatus(), 9)) {
                    inquiry.setInquiryStatus(9);
                    inquiry.setModifiedId(user.getId());
                    int update1 = inquiryMapper.updateById(inquiry);
                    if (update1 <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
            if (tripSchedule.getQuotationId() != null) {
                CustomizedQuotation quotation = quotationMapper.selectById(tripSchedule.getQuotationId());
                if (Objects.equals(quotation.getIsDeleted(), 0) && !Objects.equals(quotation.getQuotationStatus(), 4)) {
                    quotation.setQuotationStatus(4);
                    quotation.setModifiedId(user.getId());
                    int update2 = quotationMapper.updateById(quotation);
                    if (update2 <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
            return Result.success(req.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.failed(new BusinessException(SystemError.SYS_500));
    }

    /**
     * 团期详情
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    public Result<TripScheduleDetailInfoResp> info(TripScheduleDetailInfoReq req, Long userId) {
        //获取团期
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        TripScheduleDetailInfoResp resp = new TripScheduleDetailInfoResp();
        //基本信息
        TripScheduleBaseInfoDTO tripScheduleBaseInfo = getTripScheduleBaseInfo(tripSchedule);
        resp.setTripScheduleBaseInfoDTO(tripScheduleBaseInfo);
        //行程信息
        TripScheduleItineraryDTO itineraryDTO = getTripScheduleItinerary(tripSchedule.getId());
        resp.setTripScheduleItinerary(itineraryDTO);
        String pdfUrl = "";
        if (itineraryDTO != null) {
            pdfUrl = itineraryDTO.getPdfUrl();
        }
        //档案列表
        List<ArchivesJson> archivesList = getArchivesList(pdfUrl, tripSchedule.getId());
        resp.setArchivesList(archivesList);
        //TODO 供應商預訂信息
        return Result.success(resp);
    }

    /**
     * 团期详情-基本内容
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    public Result<TripScheduleBaseInfoDTO> detailBase(TripScheduleDetailInfoReq req, Long userId) {
        //获取团期
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //基本信息
        TripScheduleBaseInfoDTO tripScheduleBaseInfo = getTripScheduleBaseInfo(tripSchedule);
        if (Objects.equals(tripScheduleBaseInfo.getTripScheduleAdvanced().getHasTeaParty(),1)){
            //茶会通知
            Result<GroupInfoDTO> result = groupDistributionService.queryById(req.getScheduleId());
            if (result == null || !result.isSuccess()){
                throw new BusinessException(SystemError.SYS_439,"导领中心",result.getMsg());
            }
            GroupInfoDTO data = result.getData();
            if (data != null){
                tripScheduleBaseInfo.setTeaPartyTime(data.getTeaPartyTime());
                tripScheduleBaseInfo.setTeaPartyRoom(data.getTeaPartyRoom());
                tripScheduleBaseInfo.setTeaAddreass(data.getTeaAddreass());
                tripScheduleBaseInfo.setGuideName(data.getGuideName());
                tripScheduleBaseInfo.setSendBackName(data.getSendBackName());
                if (CollectionUtils.isNotEmpty(data.getTeaPartyHost())){
                    List<TeaPartyHostDTO> teaPartyHost = EntityUtil.copyList(data.getTeaPartyHost(),TeaPartyHostDTO.class);
                    tripScheduleBaseInfo.setTeaPartyHost(teaPartyHost);
                }
            }
        }
        return Result.success(tripScheduleBaseInfo);
    }

    /**
     * 团期详情-行程安排
     *
     * @param req
     * @return
     */
    @Override
    public Result<TripScheduleItineraryDTO> detailTrip(TripScheduleDetailInfoReq req) {
        //获取团期
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //行程信息
        TripScheduleItineraryDTO itineraryDTO = getTripScheduleItinerary(tripSchedule.getId());
        return Result.success(itineraryDTO);
    }

    /**
     * 团期详情-檔案總管理
     *
     * @param req
     * @return
     */
    @Override
    public Result<List<ArchivesJson>> detailArchives(TripScheduleDetailInfoReq req) {
        //获取团期
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //行程信息
        TripScheduleItineraryDTO itineraryDTO = getTripScheduleItinerary(tripSchedule.getId());
        String pdfUrl = "";
        if (itineraryDTO != null) {
            pdfUrl = itineraryDTO.getPdfUrl();
        }
        //档案列表
        List<ArchivesJson> archivesList = getArchivesList(pdfUrl, tripSchedule.getId());
        return Result.success(archivesList);
    }

    /**
     * 添加旅客时获取团期信息
     *
     * @param scheduleId
     * @param touristTypeId
     * @return
     */
    @Override
    public AddTouristTripScheduleDTO getAddTouristTripSchedule(Long scheduleId, Long touristTypeId) {
        AddTouristTripScheduleDTO dto = new AddTouristTripScheduleDTO();
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(scheduleId);
        if (tripSchedule == null) {
            return null;
        }
        dto.setGroupStatus(tripSchedule.getGroupStatus());
        dto.setLockStatus(tripSchedule.getLockStatus());
        //查询旅客类型信息
        QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
        touristTypeWrapper.eq("schedule_id", scheduleId);
        touristTypeWrapper.eq("main_data_id", touristTypeId);
        touristTypeWrapper.eq("is_deleted", 0);
        touristTypeWrapper.isNull("package_id");
        CustomizedQuotationTouristType touristType = quotationTouristTypeMapper.selectOne(touristTypeWrapper);
        if (touristType != null) {
            TripScheduleTouristDTO touristDTO = EntityUtil.copy(touristType, TripScheduleTouristDTO.class);
            touristDTO.setTouristTypeName(touristType.getName());
            dto.setTouristDTO(touristDTO);
        }
        //代收费用
        //旅客类型代收费用列表
        List<TouristCollectionItemDTO> collectionItemList = tripScheduleCollectionTouristFeeMapper.sumCollectionItemList(touristTypeId, scheduleId);
        if (CollectionUtils.isNotEmpty(collectionItemList)) {
            BigDecimal price = BigDecimal.ZERO;
            for (TouristCollectionItemDTO itemDTO : collectionItemList) {
                price = price.add(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()));
            }
            dto.setColletionFee(price);
            dto.setCollectionItemList(collectionItemList);
        }
        return dto;
    }

    /**
     * 获取团期旅客类型信息
     *
     * @param scheduleId
     * @param touristTypeId
     * @return
     */
    @Override
    public TripScheduleTouristDTO getTripScheduleTourist(Long scheduleId, Long touristTypeId) {
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(scheduleId);
        if (tripSchedule == null) {
            return null;
        }
        //查询旅客类型信息
        QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
        touristTypeWrapper.eq("schedule_id", scheduleId);
        touristTypeWrapper.eq("main_data_id", touristTypeId);
        touristTypeWrapper.eq("is_deleted", 0);
        CustomizedQuotationTouristType touristType = quotationTouristTypeMapper.selectOne(touristTypeWrapper);
        if (touristType != null) {
            TripScheduleTouristDTO touristDTO = EntityUtil.copy(touristType, TripScheduleTouristDTO.class);
            touristDTO.setTouristTypeName(touristType.getName());
            return touristDTO;
        }
        return null;
    }

    /**
     * 操作订单-调整项目列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<TripScheduleAdjustProjectDTO> adjustProjectList(TripScheduleAdjustProjectListReq req) {
        TripScheduleAdjustProjectDTO dto = new TripScheduleAdjustProjectDTO();
        //增减团费
        List<FeeAdjustSaveDTO> feeAdjustList = getTripScheduleFeeAdjustList(req.getScheduleId());
        feeAdjustList.forEach(feeAdjustSaveReq -> {
            feeAdjustSaveReq.setCostAmount(feeAdjustSaveReq.getCostAmount().multiply(new BigDecimal(feeAdjustSaveReq.getCurrency().getMarketExchangeRate())));
        });
        dto.setFeeAdjustList(feeAdjustList);
        //签证
        List<VisaDetailDTO> visaList = tripScheduleVisaMapper.queryBySchedule(req.getScheduleId());
        System.out.println("签证列表 ===> " + JSON.toJSONString(visaList));
        if (CollectionUtils.isNotEmpty(visaList)) {
            for (VisaDetailDTO visa : visaList) {
                //计算签证单价
                if (visa.getAdjustType().intValue() == NumberConstant.ONE.getValue()) {
                    //按金额
                    BigDecimal singlePrice = visa.getCostAmount().add(visa.getAmount());
                    visa.setSinglePrice(singlePrice.multiply(visa.getPlannedExchangeRate()));
                } else {
                    //按百分比
                    BigDecimal singlePrice = visa.getCostAmount().add(visa.getCostAmount().multiply(visa.getPercent())).setScale(2, BigDecimal.ROUND_HALF_UP);
                    visa.setSinglePrice(singlePrice.multiply(visa.getPlannedExchangeRate()));
                }
            }
            dto.setVisaList(visaList);
        }
        //更改资料收费规则
        QueryWrapper<CustomizedTripScheduleInfoChangeRule> changeRuleWrapper = new QueryWrapper<>();
        changeRuleWrapper.eq("schedule_id", req.getScheduleId());
        changeRuleWrapper.eq("is_deleted", 0);
        List<CustomizedTripScheduleInfoChangeRule> ruleList = tripScheduleInfoChangeRuleMapper.selectList(changeRuleWrapper);
        if (ruleList != null && ruleList.size() > 0) {
            List<TripScheduleChangeRuleDTO> ruleDTOList = new ArrayList<>();
            for (CustomizedTripScheduleInfoChangeRule rule : ruleList) {
                TripScheduleChangeRuleDTO ruleDTO = EntityUtil.copy(rule, TripScheduleChangeRuleDTO.class);
                ruleDTOList.add(ruleDTO);
            }
            dto.setRuleDTOList(ruleDTOList);
        }
        return Result.success(dto);
    }

    /**
     * 团期保险列表
     *
     * @param scheduleId
     * @return
     */
    @Override
    public List<TripScheduleInsuranceDTO> getInsuranceList(Long scheduleId) {
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(scheduleId);
        //當前時間 < 出發時間時才可购买
        if (tripSchedule.getDepartureDate().compareTo(LocalDateTime.now()) < NumberConstant.ZERO.getValue()) {
            throw new BusinessException(SystemError.CUSTOM_3011);
        }
        List<TripScheduleInsuranceDTO> insuranceDTOList = tripScheduleInsuranceMapper.queryListBySchedule(scheduleId);
        return insuranceDTOList;
    }


    /**
     * 团期操作-茶会通知
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result teaPartyNotice(TripScheduleTeaPartyNoticeReq req, TokenUser currentUser) {
        CustomizedTripSchedule tripSchedule = getById(req.getId());
        if (tripSchedule == null || Objects.equals(tripSchedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        QueryWrapper<CustomizedTripScheduleAdvanced> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("schedule_id", tripSchedule.getId());
        CustomizedTripScheduleAdvanced advanced = tripScheduleAdvancedMapper.selectOne(queryWrapper);
        if (advanced == null) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        if (!Objects.equals(advanced.getHasTeaParty(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3016);
        }
        //更新
        advanced.setTeaPartyTime(req.getTeaPartyTime());
        advanced.setTeaPartyDate(req.getTeaPartyDate());
        advanced.setTeaPartyRemark(req.getRemark());
        advanced.setTeaPartyLocId(req.getTeaPartyPlaceId());
        int update = tripScheduleAdvancedMapper.updateById(advanced);
        if (update <= 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        TeaPartyAddReq addReq = new TeaPartyAddReq();
        addReq.setGroupType(2);
        addReq.setGroupStatus(tripSchedule.getGroupStatus());
        addReq.setGroupId(tripSchedule.getId());
        addReq.setGroupNumber(tripSchedule.getTripNumber());
        addReq.setDays(tripSchedule.getTravelDays());
        CustomizedTripScheduleAmountStatistics statistics = tripScheduleAmountStatisticsMapper.queryBySchedule(tripSchedule.getId());
        if (statistics != null) {
            addReq.setReceivedNumber(statistics.getOrderPeople());
        }
        addReq.setTeaPartyTime(LocalDateTime.of(req.getTeaPartyDate(), req.getTeaPartyTime()));
        addReq.setDepartureDate(tripSchedule.getDepartureDate());
        addReq.setTeaPartyAreaId(req.getTeaPartyPlaceId());
        addReq.setTeaPartyAreaName(req.getTeaPartyPlace());
        addReq.setBadgeColorId(advanced.getBadgeColorId());
        addReq.setBadgeColor(advanced.getBadgeColor());
        addReq.setTeaPartyRoom(req.getTeaPartyRoom());
        Result add = teaPartyService.add(addReq, currentUser);
        if (!add.isSuccess()) {
            throw new BusinessException(SystemError.SYS_439, "导领中心", add.getMsg());
        }
        return Result.success();
    }

    /**
     * 团期操作-财务锁定状态修改
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result lockStatus(TripScheduleAdjustProjectListReq req, Long userId) {
        CustomizedTripSchedule schedule = getById(req.getScheduleId());
        if (schedule == null || Objects.equals(schedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        int lockStatus = 0;
        if (schedule.getLockStatus() == null || Objects.equals(schedule.getLockStatus(), 0)) {
            lockStatus = 1;
        }
        schedule.setLockStatus(lockStatus);
        schedule.setModifiedId(userId);
        boolean update = updateById(schedule);
        if (!update) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(schedule.getId());
    }

    /**
     * 查询团期状态（内部接口）
     *
     * @param idList
     * @return
     */
    @Override
    public List<TripScheduleGuideDTO> getScheduleList(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            throw new BusinessException(SystemError.SYS_402);
        }
        return tripScheduleMapper.getScheduleList(idList);
    }

    /**
     * 根据团号获取团期ID
     *
     * @param tripNumber
     * @return
     */
    @Override
    public Long queryIdByTripNumber(String tripNumber) {
        return tripScheduleMapper.queryIdByTripNumber(tripNumber);
    }

    /**
     * 获取团期加幅后团费（内部接口）
     *
     * @param groupFee
     * @param scheduleId
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getScheduleAddAmount(BigDecimal groupFee, Long scheduleId, Long userId) {
        QueryWrapper<CustomizedTripScheduleChannel> channelWrapper = new QueryWrapper<>();
        channelWrapper.eq("schedule_id", scheduleId);
        channelWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleChannel channel = tripScheduleChannelMapper.selectOne(channelWrapper);
        if (channel == null){
            throw new BusinessException(SystemError.CUSTOM_3018);
        }
        //类型。1：自营禁售，2：所有部门，3：指定部门/人员
        if (Objects.equals(channel.getVisableType(),2)){
            if (Objects.equals(channel.getAdjustType(),1)){
                //按数值
                groupFee = groupFee.add(channel.getAmount());
            }else if (Objects.equals(channel.getAdjustType(),2)){
                //按百分比
                groupFee = groupFee.add(groupFee.multiply(channel.getPercent())).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
        }else if (Objects.equals(channel.getVisableType(),3)){
            UserDTO userDTO = sysUserService.queryCacheUser(userId);
            if (userDTO != null){
                CustomizedTripScheduleChannelDetail detail = tripScheduleChannelDetailMapper.queryByDept(userDTO.getDeptId(),channel.getId());
                if (detail != null){
                    if (Objects.equals(detail.getAdjustType(),1)){
                        //按数值
                        groupFee = groupFee.add(detail.getAmount());
                    }else if (Objects.equals(detail.getAdjustType(),2)){
                        //按百分比
                        groupFee = groupFee.add(groupFee.multiply(detail.getPercent())).setScale(2,BigDecimal.ROUND_HALF_UP);
                    }
                }
            }
        }
        return groupFee;
    }


    /**
     * 团期操作
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result operateTrip(TripScheduleOperateReq req, TokenUser currentUser) {
        CustomizedTripSchedule tripSchedule = getById(req.getTripScheduleId());
        if (tripSchedule == null || Objects.equals(tripSchedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //操作类型(1 不成团 2 成团 3 完团 4 通知派團)
        if (Objects.equals(req.getType(), 1)) {
            if (!Objects.equals(tripSchedule.getGroupStatus(), 1) && !Objects.equals(tripSchedule.getGroupStatus(), 3)) {
                throw new BusinessException(SystemError.CUSTOM_3012);
            }
            tripSchedule.setGroupStatus(2);
            //不成团自动退保险
            Result result = customizedOrderTouristRefundService.refundInsuranceBySchedule(req.getTripScheduleId(), currentUser.getId());
            if (result == null || result.getCode() != 0) {
                throw new BusinessException(SystemError.SYS_437);
            }
        } else if (Objects.equals(req.getType(), 2)) {
            if (!Objects.equals(tripSchedule.getGroupStatus(), 1)) {
                throw new BusinessException(SystemError.CUSTOM_3012);
            }
            tripSchedule.setGroupStatus(3);
        } else if (Objects.equals(req.getType(), 3)) {
            if (!Objects.equals(tripSchedule.getGroupStatus(), 1) && !Objects.equals(tripSchedule.getGroupStatus(), 3)) {
                throw new BusinessException(SystemError.CUSTOM_3012);
            }
            //    tripSchedule.setGroupStatus(4);
            //完团需要审批
            Long approvalId = startApproval(tripSchedule.getId(), tripSchedule.getId(), currentUser.getId(), null);
            tripSchedule.setApprovalStatus(2);
            tripSchedule.setApprovalId(approvalId);
        } else {
            //通知派团
            if (!Objects.equals(tripSchedule.getGroupStatus(), 1) && !Objects.equals(tripSchedule.getGroupStatus(), 3)) {
                throw new BusinessException(SystemError.CUSTOM_3012);
            }
            GroupDistributionAddReq addReq = new GroupDistributionAddReq();
            addReq.setGroupId(tripSchedule.getId());
            addReq.setGroupStatus(tripSchedule.getGroupStatus());
            addReq.setGroupType(2);
            addReq.setGroupNumber(tripSchedule.getTripNumber());
            addReq.setDays(tripSchedule.getTravelDays());
            addReq.setRequirement(req.getRequire());
            CustomizedTripScheduleAmountStatistics statistics = tripScheduleAmountStatisticsMapper.queryBySchedule(tripSchedule.getId());
            if (statistics != null) {
                addReq.setReceivedNumber(statistics.getOrderPeople());
                addReq.setTotalNumber(statistics.getTotalPeople());
            }
            QueryWrapper<CustomizedTripScheduleAdvanced> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("schedule_id", tripSchedule.getId());
            CustomizedTripScheduleAdvanced advanced = tripScheduleAdvancedMapper.selectOne(queryWrapper);
            if (advanced != null) {
                LocalDateTime aggregateTime = LocalDateTime.of(tripSchedule.getDepartureDate().toLocalDate(), advanced.getDepartureTime());
                addReq.setAggregateTime(aggregateTime);
                LocalDateTime scatteredTime = LocalDateTime.of(tripSchedule.getDepartureDate().plusDays(tripSchedule.getTravelDays()).toLocalDate(), advanced.getDissolutionTime());
                addReq.setScatteredTime(scatteredTime);
                addReq.setCollectionPlaceAreaId(advanced.getCollectionAreaId());
                addReq.setCollectionPlaceAreaName(advanced.getCollectionArea());
                addReq.setIsTips(advanced.getNeedTripConsumption());
            }
            addReq.setTripTitle(tripSchedule.getName());
            addReq.setType(req.getNoticeType());
            addReq.setStatus(1);
            Result add = groupDistributionService.add(addReq, currentUser);
            if (add == null || add.getCode() != 0) {
                throw new BusinessException(SystemError.SYS_431, "导领中心");
            }
        }
        tripSchedule.setModifiedId(currentUser.getId());
        boolean update = updateById(tripSchedule);
        if (!update) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(tripSchedule.getId());
    }


    /**
     * 发起审批流程
     *
     * @param id
     * @param orderId
     * @param userId
     */
    private Long startApproval(Long id, Long orderId, Long userId, BigDecimal amount) {
        Map<String, Object> extendParams = new HashMap<>();
        extendParams.put("id", id);
        try {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode(),
                    SysApprovalType.TRAVEl_OUTCUSTOM.getCode(), orderId,
                    userId, amount, JSON.toJSONString(extendParams));
            if (!approvalResult.isSuccess()) {
                throw new BusinessException(SystemError.CUSTOM_ORDER_4044);
            }
            return approvalResult.getData().getApprovalId();
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_422);
        }
    }


    /**
     * 财务中心-特殊收款-根据ID获取团期详情（内部接口）
     *
     * @param id
     * @return
     */
    @Override
    public TripScheduleDTO queryById(Long id) {
        TripScheduleDTO dto = null;
        CustomizedTripSchedule tripSchedule = getById(id);
        if (tripSchedule != null && Objects.equals(tripSchedule.getIsDeleted(), 0)) {
            dto = EntityUtil.copy(tripSchedule, TripScheduleDTO.class);
            String weekDay = CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue());
            dto.setDepartureDateWeekDate(weekDay);
        }
        return dto;
    }

    /**
     * 根据ID列表获取团期详情列表（内部接口）
     *
     * @param idList
     * @param departType
     * @return
     */
    @Override
    public List<TripScheduleDTO> queryByIds(List<Long> idList, Integer departType) {
        List<TripScheduleDTO> list = null;
        QueryWrapper<CustomizedTripSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("depart_type", departType);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.in("id", idList);
        List<CustomizedTripSchedule> scheduleList = tripScheduleMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(scheduleList)) {
            list = EntityUtil.copyList(scheduleList, TripScheduleDTO.class);
            list.forEach(dto -> {
                String weekDay = CharUtil.getWeekDay(dto.getDepartureDate().getDayOfWeek().getValue());
                dto.setDepartureDateWeekDate(weekDay);
            });
        }
        return list;
    }

    /**
     * 定制包团列表(其他模块调用)
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<TripScheduleDTO> scheduleList(ScheduleListReq req) {
        Page<CustomizedTripSchedule> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<CustomizedTripSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getTripNumber()), "trip_number", req.getTripNumber());
        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());
        queryWrapper.eq(req.getDeparturePlaceId() != null, "departure_place_id", req.getDeparturePlaceId());
        queryWrapper.eq(req.getDestinationId() != null, "destination_id", req.getDestinationId());
        queryWrapper.between(req.getBeginDate() != null && req.getEndDate() != null, "departure_date", req.getBeginDate(), req.getEndDate());
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.orderByDesc("gmt_create");
        Page<CustomizedTripSchedule> page = tripScheduleMapper.selectPage(iPage, queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return PageResponse.empty(page.getCurrent());
        }
        List<TripScheduleDTO> list = EntityUtil.copyList(page.getRecords(), TripScheduleDTO.class);
        list.forEach(dto -> {
            String weekDay = CharUtil.getWeekDay(dto.getDepartureDate().getDayOfWeek().getValue());
            dto.setDepartureDateWeekDate(weekDay);
        });
        PageResponse<TripScheduleDTO> result = new PageResponse<>(list, page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    /**
     * 完团审批
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result approval(TripScheduleApprovalReq req) {
        CustomizedTripSchedule tripSchedule = getById(req.getId());
        if (tripSchedule == null || Objects.equals(tripSchedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        if (!Objects.equals(tripSchedule.getApprovalStatus(), 2)) {
            throw new BusinessException(SystemError.FINANCE_BILL_17012);
        }
        tripSchedule.setApprovalStatus(req.getType());
        tripSchedule.setGroupStatus(4);
        tripSchedule.setModifiedId(req.getUserId());
        boolean update = updateById(tripSchedule);
        if (!update) {
            throw new BusinessException(SystemError.SYS_437);
        }
        Result<ApprovalCheckDTO> result = sysApprovalService.check(tripSchedule.getApprovalId(), req.getUserId(), req.getType(), req.getRemark());
        if (result == null || !result.getData().getIsFinish()) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(tripSchedule.getId());
    }

    /**
     * 旅客名单-团期信息
     *
     * @param scheduleId
     * @return
     */
    @Override
    public Result<TouristScheduleInfoDTO> touristScheduleInfo(Long scheduleId) {
        CustomizedTripSchedule tripSchedule = getById(scheduleId);
        if (tripSchedule == null || Objects.equals(tripSchedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        TouristScheduleInfoDTO dto = new TouristScheduleInfoDTO();
        dto.setTripNumber(tripSchedule.getTripNumber());
        dto.setGroupStatus(tripSchedule.getGroupStatus());
        dto.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
        //获取余位数
        CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(scheduleId);
        if (amountStatistics != null) {
            dto.setTouristNum(amountStatistics.getTotalPeople() - amountStatistics.getOrderPeople());
        }
        //报名人数
        List<TouristTypeCountDTO> touristList = tripScheduleTouristCountMapper.queeryBySchedule(scheduleId);
        if (CollectionUtils.isNotEmpty(touristList)) {
            dto.setTouristList(touristList);
        }
        return Result.success(dto);
    }


    /**
     * 定制包团下单页面信息
     *
     * @param req
     * @return
     */
    @Override
    public Result<ScheduleOrderPageInfoDTO> createOrderInfo(TripScheduleDetailInfoReq req) {
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(req.getScheduleId());
        if (tripSchedule == null || Objects.equals(tripSchedule.getIsDeleted(), 1)) {
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        ScheduleOrderPageInfoDTO orderPageInfoDTO = EntityUtil.copy(tripSchedule, ScheduleOrderPageInfoDTO.class);
        if (tripSchedule.getDepartureDate() != null) {
            //出发日期星期几
            orderPageInfoDTO.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
            String departureWeekDay = CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue());
            orderPageInfoDTO.setDepartureWeekDay(departureWeekDay);
        }
        if (tripSchedule.getTravelDays() != null) {
            //返回日期
            LocalDate returnDate = tripSchedule.getDepartureDate().toLocalDate().plusDays(tripSchedule.getTravelDays());
            orderPageInfoDTO.setReturnDate(returnDate);
            String returnWeekDay = CharUtil.getWeekDay(returnDate.getDayOfWeek().getValue());
            orderPageInfoDTO.setReturnWeekDay(returnWeekDay);
        }
        if (tripSchedule.getChargePersonId() != null) {
            UserDTO userDTO = sysUserService.queryCacheUser(tripSchedule.getChargePersonId());
            if (userDTO != null) {
                //负责人部门
                orderPageInfoDTO.setChargePersonDept(userDTO.getDept());
            }
        }
        //获取联络人信息和旅客信息
        orderPageInfoDTO = saveContactAndTouristInfo(tripSchedule, orderPageInfoDTO);
        //套餐总费用
        BigDecimal totalAmount = BigDecimal.ZERO;
        //总人数
        Integer peopleNum = 0;
        //自由报价按服务-总单价
        BigDecimal totalSinglePrice = BigDecimal.ZERO;
        //代收费用
        CollectionJson collectionJson = getTripScheduleCollectionFeeList(tripSchedule.getId(), BigDecimal.ZERO);
        orderPageInfoDTO.setCollectionFees(collectionJson.getCollectionFees());
        orderPageInfoDTO.setTotalCollectionFee(collectionJson.getTotalCollectionFee());
        TripSchedulePackageJson packageJson = null;
        if (tripSchedule.getQuotationType().intValue() == NumberConstant.ONE.getValue()) {
            //自由报价
            //获取套餐
            QueryWrapper<CustomizedTripScheduleFreeQuotePackage> packageWrapper = new QueryWrapper<>();
            packageWrapper.eq("schedule_id", tripSchedule.getId());
            packageWrapper.eq("is_deleted", 0);
            packageWrapper.orderByAsc("sort");
            List<CustomizedTripScheduleFreeQuotePackage> packageList = tripScheduleFreeQuotePackageMapper.selectList(packageWrapper);
            if (packageList != null && packageList.size() > 0) {
                //自由报价
                packageJson = getTripScheduleFreePackageList(packageList, totalAmount, totalSinglePrice);
                orderPageInfoDTO.setReqPackages(packageJson.getReqPackageReqs());
                orderPageInfoDTO.setFreeTotalSinglePrice(packageJson.getTotalSinglePrice());
            }
        } else {
            //行程报价
            QueryWrapper<CustomizedTripScheduleDate> dateWrapper = new QueryWrapper<>();
            dateWrapper.eq("schedule_id", tripSchedule.getId());
            dateWrapper.eq("is_deleted", 0);
            dateWrapper.orderByAsc("day");
            List<CustomizedTripScheduleDate> dateList = tripScheduleDateMapper.selectList(dateWrapper);
            if (dateList != null && dateList.size() > 0) {
                packageJson = getTripScheduleTripQuoteList(dateList, totalAmount, peopleNum);
                orderPageInfoDTO.setTripQuoteReqs(packageJson.getTripQuoteReqs());
                //旅客人数数组
                List<QuotationTouristTypeReq> touristTypes = getTripScheduleTouristTypeList(tripSchedule.getId());
                orderPageInfoDTO.setTouristTypes(touristTypes);
                //行程报价总单价
                BigDecimal quoteTotalSinglePrice = tripScheduleDateMapper.sumSinglePrice(tripSchedule.getId());
                orderPageInfoDTO.setQuoteTotalSinglePrice(quoteTotalSinglePrice);
            }
        }
        if (packageJson != null) {
            orderPageInfoDTO.setTotalAmount(packageJson.getTotalAmount());
            orderPageInfoDTO.setPeopleNum(packageJson.getPeopleNum());
        }
        return Result.success(orderPageInfoDTO);
    }


    /**
     * 团期详情 - 行程信息
     *
     * @param scheduleId
     * @return
     */
    private TripScheduleItineraryDTO getTripScheduleItinerary(Long scheduleId) {
        QueryWrapper<CustomizedTripScheduleItinerary> itineraryWrapper = new QueryWrapper<>();
        itineraryWrapper.eq("schedule_id", scheduleId);
        itineraryWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleItinerary itinerary = tripScheduleItineraryMapper.selectOne(itineraryWrapper);
        if (itinerary != null) {
            TripScheduleItineraryDTO itineraryDTO = EntityUtil.copy(itinerary, TripScheduleItineraryDTO.class);
            itineraryDTO.setId(itinerary.getId());
            //自费项目
            if (StringUtils.isNotBlank(itinerary.getSelfFeeJson())) {
                List<SelfFeeJson> selfFeeJsonList = JSON.parseArray(itinerary.getSelfFeeJson(), SelfFeeJson.class);
                itineraryDTO.setSelfFeeJsonList(selfFeeJsonList);
            }
            //团期行程每日介绍
            QueryWrapper<CustomizedTripScheduleItineraryDay> itineraryDayWrapper = new QueryWrapper<>();
            itineraryDayWrapper.eq("itinerary_id", itinerary.getId());
            itineraryDayWrapper.eq("is_deleted", 0);
            itineraryDayWrapper.orderByAsc("day");
            List<CustomizedTripScheduleItineraryDay> itineraryDayList = tripScheduleItineraryDayMapper.selectList(itineraryDayWrapper);
            if (itineraryDayList != null) {
                List<TripScheduleItineraryDayDTO> itineraryDayDTOList = new ArrayList<>();
                itineraryDayList.forEach(itineraryDay -> {
                    TripScheduleItineraryDayDTO dayDTO = new TripScheduleItineraryDayDTO();
                    dayDTO.setDay(itineraryDay.getDay());
                    dayDTO.setTitle(itineraryDay.getTitle());
                    dayDTO.setTrafficRemark(itineraryDay.getTrafficRemark());
                    dayDTO.setFoodRemark(itineraryDay.getFoodRemark());
                    dayDTO.setHotelRemark(itineraryDay.getHotelRemark());
                    dayDTO.setDayRemark(itineraryDay.getDayRemark());
                    if (StringUtils.isNotBlank(itineraryDay.getTrafficJson())) {
                        List<TrafficJson> trafficJson = JSON.parseArray(itineraryDay.getTrafficJson(), TrafficJson.class);
                        dayDTO.setTrafficJson(trafficJson);
                    }
                    if (StringUtils.isNotBlank(itineraryDay.getFoodJson())) {
                        FoodJson foodJson = JSON.parseObject(itineraryDay.getFoodJson(), FoodJson.class);
                        if (foodJson != null) {
                            dayDTO.setFoodBreakfast(foodJson.getFoodBreakfast());
                            dayDTO.setFoodLunch(foodJson.getFoodLunch());
                            dayDTO.setFoodSupper(foodJson.getFoodSupper());
                            dayDTO.setFoodPhotoJson(foodJson.getFoodPhotoJson());
                        }
                    }
                    if (StringUtils.isNotBlank(itineraryDay.getHotelJson())) {
                        List<HotelJson> hotelJson = JSON.parseArray(itineraryDay.getHotelJson(), HotelJson.class);
                        dayDTO.setHotelJson(hotelJson);
                    }
                    if (StringUtils.isNotBlank(itineraryDay.getScenicJson())) {
                        List<ScenicJson> scenicJson = JSON.parseArray(itineraryDay.getScenicJson(), ScenicJson.class);
                        dayDTO.setScenicJson(scenicJson);
                    }
                    itineraryDayDTOList.add(dayDTO);
                });
                itineraryDTO.setItineraryDayList(itineraryDayDTOList);
            }
            return itineraryDTO;
        }
        return null;
    }


    /**
     * 保存团期基本信息 - 设置团期属性
     *
     * @param tripSchedule
     * @param req
     * @param userId
     * @return
     */
    private CustomizedTripSchedule saveTripScheduleAttr(CustomizedTripSchedule tripSchedule, SaveTripScheduleBaseInfoReq req, Long userId) {
        tripSchedule.setGroupStatus(NumberConstant.FIVE.getValue());
        tripSchedule.setDepartType(req.getDepartType());
        tripSchedule.setId(SnowflakeIdWorker.nextId());
        try {
            UserDTO userDTO = sysUserService.queryCacheUser(userId);
            SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryOne(userDTO.getDeptId());
            //操作人当天出发团期总数
            QueryWrapper<CustomizedTripSchedule> tripScheduleWrapper = new QueryWrapper<>();
            tripScheduleWrapper.eq("create_id", userId);
            tripScheduleWrapper.eq("departure_date", DateUtil.fmtLocalDate(req.getDepartureDate(), "yyyy-MM-dd 00:00:00"));
            tripScheduleWrapper.eq("is_deleted", 0);
            Integer count = tripScheduleMapper.selectCount(tripScheduleWrapper);
            //旅游组别码
            String groupCode = "";
            MainDataTourGroupCodeUpdateStatusReq groupCodeUpdateStatusReq = new MainDataTourGroupCodeUpdateStatusReq();
            groupCodeUpdateStatusReq.setId(req.getTourTypeId());
            Result<MainDataTourGroupCodeQueryDTO> query = tourGroupCodeService.query(groupCodeUpdateStatusReq);
            if (query != null && query.isSuccess()){
                groupCode = query.getData().getTourGroupCode();
            }
            //生成团号 生成规则：FR20OV1220T02128A（FR- 部门代号、20-年份、OV- 旅遊組別财务碼代号、1220-团隊出发日期，12月20日、T02128-经办同事工号、A- 出发当天第一个团
            String tripNumber = sysDepartmentDTO.getDeptCode() + DateUtil.fmtYear(LocalDate.now()) +
                    groupCode + DateUtil.fmtMd(req.getDepartureDate()) + userDTO.getEmployeeNumber() + CharUtil.getChar(count);
            tripSchedule.setTripNumber(tripNumber);
            tripSchedule.setGmtCreate(LocalDateTime.now());
            tripSchedule.setCreateId(userId);
            tripSchedule.setIsDeleted(0);
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_417);
        }
        return tripSchedule;
    }


    /**
     * 保存团期基本信息 - 处理团队高级设置
     *
     * @param req
     * @param scheduleId
     * @param userId
     */
    private void dealTripScheduleAdvanced(SaveTripScheduleBaseInfoReq req, Long scheduleId, Long userId, Integer operateType) {
        //团队高级设置
        if (req.getAdvancedReq() != null) {
            //封装团队高级设置属性
            CustomizedTripScheduleAdvanced advanced = saveTripScheduleAdvanced(req, operateType);
            int advancedResult = 0;
            if (advanced.getId() == null) {
                //新增
                advanced.setId(SnowflakeIdWorker.nextId());
                advanced.setCreateId(userId);
                advanced.setScheduleId(scheduleId);
                advanced.setGmtCreate(LocalDateTime.now());
                advanced.setIsDeleted(0);
                advancedResult = tripScheduleAdvancedMapper.insert(advanced);
            } else {
                //修改
                CustomizedTripScheduleAdvanced before = tripScheduleAdvancedMapper.selectById(advanced.getId());
                CustomizedTripSchedule schedule = getById(scheduleId);
                //对比集合时间和散团时间是否修改
                //旧数据
                if (before.getCollectionTime() != null && before.getCollectionDateType() != null && before.getDissolutionTime() != null && before.getDissolutionDateType() != null) {
                    LocalDate collectionDate = schedule.getDepartureDate().toLocalDate();
                    if (Objects.equals(before.getCollectionDateType(), 2)) {
                        collectionDate = schedule.getDepartureDate().toLocalDate().minusDays(1l);
                    }
                    //集合时间
                    LocalDateTime collectionTime = LocalDateTime.of(collectionDate, before.getCollectionTime());
                    LocalDate dissolutionDate = schedule.getDepartureDate().toLocalDate().plusDays(schedule.getTravelDays().longValue());
                    if (Objects.equals(before.getDissolutionDateType(), 2)) {
                        dissolutionDate = schedule.getDepartureDate().toLocalDate().plusDays(1l);
                    }
                    //散团时间
                    LocalDateTime dissolutionTime = LocalDateTime.of(dissolutionDate, before.getDissolutionTime());
                    //新数据
                    if (advanced.getCollectionTime() != null && advanced.getCollectionDateType() != null && advanced.getDissolutionTime() != null && advanced.getDissolutionDateType() != null) {
                        LocalDate collectionDate2 = req.getDepartureDate();
                        if (Objects.equals(advanced.getCollectionDateType(), 2)) {
                            collectionDate2 = req.getDepartureDate().minusDays(1l);
                        }
                        //集合时间
                        LocalDateTime collectionTime2 = LocalDateTime.of(collectionDate2, advanced.getCollectionTime());
                        LocalDate dissolutionDate2 = req.getDepartureDate().plusDays(req.getTravelDays().longValue());
                        if (Objects.equals(advanced.getDissolutionDateType(), 2)) {
                            dissolutionDate2 = req.getDepartureDate().plusDays(1l);
                        }
                        //散团时间
                        LocalDateTime dissolutionTime2 = LocalDateTime.of(dissolutionDate2, advanced.getDissolutionTime());
                        if (!Objects.equals(collectionTime, collectionTime2) || !Objects.equals(dissolutionTime, dissolutionTime2)) {
                            //有改动
                            GroupDistributionIdUpdateStatusReq updateReq = new GroupDistributionIdUpdateStatusReq();
                            updateReq.setGroupId(scheduleId);
                            updateReq.setGroupType(GroupDistributionGroupType.CUSTOMIZE.getCode());
                            updateReq.setBeginTime(collectionTime2);
                            updateReq.setEndTime(dissolutionTime2);
                            Result result = groupDistributionService.updateTime(updateReq, userId);
                            if (result == null || !result.isSuccess()) {
                                throw new BusinessException(SystemError.SYS_437);
                            }
                        }
                    }
                }
                advanced.setModifiedId(userId);
                advancedResult = tripScheduleAdvancedMapper.updateById(advanced);
            }
            if (advancedResult <= 0) {
                throw new BusinessException(SystemError.SYS_437);
            }
            TripScheduleAdvancedReq advancedReq = req.getAdvancedReq();
            //旅客资料收费规则
            if (advancedReq.getChangeRuleReqList() != null && advancedReq.getChangeRuleReqList().size() > 0) {
                //清空团期资料收费规则
                tripScheduleInfoChangeRuleMapper.clearBySchedule(scheduleId, userId);
                List<CustomizedTripScheduleInfoChangeRule> ruleList = new ArrayList<>();
                for (TripScheduleInfoChangeRuleReq ruleReq : advancedReq.getChangeRuleReqList()) {
                    if (ruleReq.getChargeAmount() == null){
                        throw new BusinessException(SystemError.SYS_409,"更改資料收費規則金額必傳");
                    }
                    CustomizedTripScheduleInfoChangeRule rule = new CustomizedTripScheduleInfoChangeRule();
                    rule.setScheduleId(scheduleId);
                    MainDataTripInfoChangeRuleIdReq changeRuleIdReq = new MainDataTripInfoChangeRuleIdReq();
                    changeRuleIdReq.setId(ruleReq.getId());
                    MainDataTripInfoChangeRuleListDTO ruleDTO = tripInfoChangeRuleService.query(changeRuleIdReq);
                    if (ruleDTO != null) {
                        rule.setName(ruleDTO.getTripInfoChangeRuleName());
                    }
                    rule.setMainDataId(ruleReq.getId());
                    rule.setAmount(ruleReq.getChargeAmount());
                    rule.setSort(ruleReq.getSort());
                    rule.setCreateId(userId);
                    rule.setGmtCreate(LocalDateTime.now());
                    rule.setIsDeleted(0);
                    ruleList.add(rule);
                }
                Integer batch = tripScheduleInfoChangeRuleMapper.insertBatchSomeColumn(ruleList);
                if (batch < ruleList.size()) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
    }

    /**
     * 保存团期基本信息 - 处理签证
     *
     * @param req
     * @param scheduleId
     * @param userId
     */
    private void dealTripScheduleVisa(SaveTripScheduleBaseInfoReq req, Long scheduleId, Long userId) {
        //查询签证
        QueryWrapper<CustomizedTripScheduleVisa> visaWrapper = new QueryWrapper<>();
        visaWrapper.eq("schedule_id", scheduleId);
        visaWrapper.eq("is_deleted", 0);
        List<CustomizedTripScheduleVisa> visaList = tripScheduleVisaMapper.selectList(visaWrapper);
        if (visaList != null && visaList.size() > 0) {
            //改为已删除
            visaList.forEach(visa -> {
                visa.setIsDeleted(1);
                visa.setModifiedId(userId);
                int update = tripScheduleVisaMapper.updateById(visa);
                if (update < 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            });
        }
        if (req.getNeedVisa().intValue() == NumberConstant.ONE.getValue()) {
            //需要签证
            if (req.getVisaAddReqList() != null && req.getVisaAddReqList().size() > 0) {
                List<CustomizedTripScheduleVisa> list = new ArrayList<>();
                for (TripScheduleVisaAddReq addReq : req.getVisaAddReqList()) {
                    CustomizedTripScheduleVisa visa = new CustomizedTripScheduleVisa();
                    visa.setScheduleId(scheduleId);
                    try {
                        Visa visa1 = visaMapper.selectById(addReq.getId());
                        if (visa1 != null) {
                            visa.setVisaId(addReq.getId());
                            visa.setName(visa1.getName());
                            visa.setCreateId(userId);
                            visa.setGmtCreate(LocalDateTime.now());
                            visa.setIsDeleted(0);
                            list.add(visa);
                        }
                    } catch (Exception e) {
                        throw new BusinessException(SystemError.SYS_417);
                    }
                }
                if (list.size() > 0) {
                    //批量新增
                    Integer batch = tripScheduleVisaMapper.insertBatchSomeColumn(list);
                    if (batch < list.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
        }
    }

    /**
     * 保存团期基本信息 - 处理保险
     *
     * @param req
     * @param scheduleId
     * @param userId
     */
    private void dealTripScheduleInsurance(SaveTripScheduleBaseInfoReq req, Long scheduleId, Long userId) {
        //查询保险计划列表
        QueryWrapper<CustomizedTripScheduleInsurance> insuranceWrapper = new QueryWrapper<>();
        insuranceWrapper.eq("schedule_id", req.getId());
        insuranceWrapper.eq("is_deleted", 0);
        List<CustomizedTripScheduleInsurance> insuranceList = tripScheduleInsuranceMapper.selectList(insuranceWrapper);
        if (insuranceList != null && insuranceList.size() > 0) {
            insuranceList.forEach(insurance -> {
                //改为已删除
                insurance.setIsDeleted(1);
                insurance.setModifiedId(userId);
                int update = tripScheduleInsuranceMapper.updateById(insurance);
                if (update < 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            });
        }
        if (req.getNeedInsurance().intValue() == NumberConstant.ONE.getValue()) {
            //需要保险
            if (req.getInsuranceAddList() != null && req.getInsuranceAddList().size() > 0) {
                List<CustomizedTripScheduleInsurance> list = new ArrayList<>();
                for (TripScheduleInsuranceAddReq addReq : req.getInsuranceAddList()) {
                    CustomizedTripScheduleInsurance insurance = new CustomizedTripScheduleInsurance();
                    insurance.setScheduleId(scheduleId);
                    try {
                        InsuranceDTO insuranceDTO = insuranceService.detail(addReq.getId());
                        System.out.println("保险 =====>>> " + insuranceDTO.toString());
                        //    MainDataFieldDataDTO insuranceDto = mainDataFieldDataService.queryFieldData(addReq.getId());
                        if (insuranceDTO != null) {
                            insurance.setInsuranceId(addReq.getId());
                            insurance.setName(insuranceDTO.getName());
                        }
                    } catch (Exception e) {
                        throw new BusinessException(SystemError.SYS_417);
                    }
                    insurance.setCreateId(userId);
                    insurance.setGmtCreate(LocalDateTime.now());
                    insurance.setIsDeleted(0);
                    list.add(insurance);
                }
                //批量新增
                if (list.size() > 0) {
                    Integer batch = tripScheduleInsuranceMapper.insertBatchSomeColumn(list);
                    if (batch < list.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
        }
    }


    /**
     * 根据询价单封装团期基本信息
     *
     * @param inquiry
     * @return
     */
    private TripScheduleBaseInfoDTO packTripScheduleBaseInfoDTOByInquiry(CustomizedInquiry inquiry) {
        TripScheduleBaseInfoDTO dto = EntityUtil.copy(inquiry, TripScheduleBaseInfoDTO.class);
        dto.setInquiryTitle(inquiry.getInquiryTitle());
        dto.setInquiryNumber(inquiry.getInquiryNumber());
        MainData bigClient = new MainData();
        bigClient.setLabel(inquiry.getBigClientName());
        bigClient.setValue(inquiry.getBigClientId());
        dto.setBigClient(bigClient);
        MainData departurePlace = new MainData();
        departurePlace.setLabel(inquiry.getDeparturePlace());
        departurePlace.setValue(inquiry.getDeparturePlaceId());
        dto.setDeparturePlace(departurePlace);
        MainData destination = new MainData();
        destination.setLabel(inquiry.getDestination());
        destination.setValue(inquiry.getDestinationId());
        dto.setDestination(destination);
        dto.setDepartureDate(inquiry.getDepartureDate());
        dto.setTravelDays(inquiry.getTravelDays());
        dto.setNightDays(inquiry.getNightDays());
        dto.setOpId(inquiry.getOpId());
        dto.setOpNumber(inquiry.getOpNumber());
        dto.setOpName(inquiry.getOpName());
        return dto;
    }

    /**
     * 团期详情 - 获取团期基本信息
     *
     * @param tripSchedule
     * @return
     */
    private TripScheduleBaseInfoDTO getTripScheduleBaseInfo(CustomizedTripSchedule tripSchedule) {
        try {
            //封装团期基本信息
            TripScheduleBaseInfoDTO dto = packTripScheduleBaseInfoDTOByTripSchedule(tripSchedule);
            //团期统计
            CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(tripSchedule.getId());
            if (amountStatistics != null) {
                dto.setTotalFee(amountStatistics.getTotalFee());
                dto.setTotalPeople(amountStatistics.getTotalPeople());
            }
            //团队高级设置
            QueryWrapper<CustomizedTripScheduleAdvanced> tripScheduleAdvancedWrapper = new QueryWrapper<>();
            tripScheduleAdvancedWrapper.eq("schedule_id", tripSchedule.getId());
            tripScheduleAdvancedWrapper.eq("is_deleted", 0);
            CustomizedTripScheduleAdvanced tripScheduleAdvanced = tripScheduleAdvancedMapper.selectOne(tripScheduleAdvancedWrapper);
            if (tripScheduleAdvanced != null) {
                //获取团期高级设置信息
                TripScheduleAdvancedDTO tripScheduleAdvancedDTO = getTripScheduleAdvanced(tripScheduleAdvanced, tripSchedule.getId());
                dto.setTripScheduleAdvanced(tripScheduleAdvancedDTO);
            }
            //保险计划
            if (tripSchedule.getNeedInsurance().intValue() == NumberConstant.ONE.getValue()) {
                List<TripScheduleInsuranceDTO> insuranceDTOList = tripScheduleInsuranceMapper.queryListBySchedule(tripSchedule.getId());
                if (insuranceDTOList == null) {
                    throw new BusinessException(SystemError.CUSTOM_3007);
                }
                dto.setTripScheduleInsuranceList(insuranceDTOList);
            }
            //签证
            if (tripSchedule.getNeedVisa().intValue() == NumberConstant.ONE.getValue()) {
                //获取团期签证
                List<TripScheduleVisaDTO> tripScheduleVisaDTOList = getTripScheduleVisa(tripSchedule.getId());
                dto.setTripScheduleVisaList(tripScheduleVisaDTOList);
            }
            System.out.println(" 返回数据 ===>>> " + dto.toString());
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取团期签证
     *
     * @param scheduleId
     * @return
     */
    private List<TripScheduleVisaDTO> getTripScheduleVisa(Long scheduleId) {
        List<TripScheduleVisaDTO> tripScheduleVisaDTOList = tripScheduleVisaMapper.queryListBySchedule(scheduleId);
        if (tripScheduleVisaDTOList == null) {
            throw new BusinessException(SystemError.CUSTOM_3008);
        }
        List<TripScheduleVisaDTO> tripScheduleVisaDTOList2 = new ArrayList<>();
        tripScheduleVisaDTOList.forEach(tripScheduleVisaDTO -> {
            //免签国家
            QueryWrapper<VisaFreeCountries> countriesWrapper = new QueryWrapper<>();
            countriesWrapper.eq("visa_id", tripScheduleVisaDTO.getVisaId());
            countriesWrapper.eq("is_deleted", 0);
            countriesWrapper.orderByAsc("gmt_create");
            List<VisaFreeCountries> freeCountriesList = visaFreeCountriesMapper.selectList(countriesWrapper);
            if (freeCountriesList != null) {
                List<VisaFreeCountriesDTO> freeCountriesDTOList = new ArrayList<>();
                freeCountriesList.forEach(visaFreeCountries -> {
                    VisaFreeCountriesDTO freeCountriesDTO = EntityUtil.copy(visaFreeCountries, VisaFreeCountriesDTO.class);
                    freeCountriesDTOList.add(freeCountriesDTO);
                });
                tripScheduleVisaDTO.setFreeCountriesList(freeCountriesDTOList);
            }
            tripScheduleVisaDTOList2.add(tripScheduleVisaDTO);
        });
        return tripScheduleVisaDTOList2;
    }

    /**
     * 获取团期高级设置信息
     *
     * @param tripScheduleAdvanced
     * @param scheduleId
     * @return
     */
    private TripScheduleAdvancedDTO getTripScheduleAdvanced(CustomizedTripScheduleAdvanced tripScheduleAdvanced, Long scheduleId) {
        //封装团期高级设置属性
        TripScheduleAdvancedDTO tripScheduleAdvancedDTO = packAdvancedParam(tripScheduleAdvanced);
        //旅客资料收费规则
        QueryWrapper<CustomizedTripScheduleInfoChangeRule> ruleWrapper = new QueryWrapper<>();
        ruleWrapper.eq("schedule_id", scheduleId);
        ruleWrapper.eq("is_deleted", 0);
        ruleWrapper.orderByAsc("sort");
        List<CustomizedTripScheduleInfoChangeRule> ruleList = tripScheduleInfoChangeRuleMapper.selectList(ruleWrapper);
        if (ruleList != null) {
            List<TripScheduleInfoChangeRuleDTO> ruleDTOList = new ArrayList<>();
            ruleList.forEach(rule -> {
                TripScheduleInfoChangeRuleDTO ruleDTO = new TripScheduleInfoChangeRuleDTO();
                ruleDTO.setChargeAmount(rule.getAmount());
                ruleDTO.setLabel(rule.getName());
                ruleDTO.setValue(rule.getMainDataId());
                ruleDTOList.add(ruleDTO);
            });
            tripScheduleAdvancedDTO.setTripScheduleInfoChangeRuleList(ruleDTOList);
        }
        return tripScheduleAdvancedDTO;
    }

    /**
     * 封装团期高级设置属性
     *
     * @param tripScheduleAdvanced
     * @return
     */
    private TripScheduleAdvancedDTO packAdvancedParam(CustomizedTripScheduleAdvanced tripScheduleAdvanced) {
        TripScheduleAdvancedDTO tripScheduleAdvancedDTO = EntityUtil.copy(tripScheduleAdvanced, TripScheduleAdvancedDTO.class);
        tripScheduleAdvancedDTO.setId(tripScheduleAdvanced.getId());
        MainData badgeColor = new MainData();
        badgeColor.setLabel(tripScheduleAdvanced.getBadgeColor());
        badgeColor.setValue(tripScheduleAdvanced.getBadgeColorId());
        tripScheduleAdvancedDTO.setBadgeColor(badgeColor);
        MainData departureArea = new MainData();
        departureArea.setValue(tripScheduleAdvanced.getDepartureAreaId());
        departureArea.setLabel(tripScheduleAdvanced.getDepartureArea());
        tripScheduleAdvancedDTO.setDepartureArea(departureArea);
        MainData collectionPlace = new MainData();
        collectionPlace.setLabel(tripScheduleAdvanced.getCollectionPlace());
        collectionPlace.setValue(tripScheduleAdvanced.getCollectionPlaceId());
        tripScheduleAdvancedDTO.setCollectionPlace(collectionPlace);
        MainData dissolutionArea = new MainData();
        dissolutionArea.setValue(tripScheduleAdvanced.getDissolutionAreaId());
        dissolutionArea.setLabel(tripScheduleAdvanced.getDissolutionArea());
        tripScheduleAdvancedDTO.setDissolutionArea(dissolutionArea);
        MainData dissolutionPlace = new MainData();
        dissolutionPlace.setLabel(tripScheduleAdvanced.getDissolutionPlace());
        dissolutionPlace.setValue(tripScheduleAdvanced.getDissolutionPlaceId());
        tripScheduleAdvancedDTO.setDissolutionPlace(dissolutionPlace);
        MainData departureTrafficType = new MainData();
        departureTrafficType.setValue(tripScheduleAdvanced.getDepartureTrafficTypeId());
        departureTrafficType.setLabel(tripScheduleAdvanced.getDepartureTrafficType());
        tripScheduleAdvancedDTO.setDepartureTrafficType(departureTrafficType);
        MainData returnTrafficType = new MainData();
        returnTrafficType.setLabel(tripScheduleAdvanced.getReturnTrafficType());
        returnTrafficType.setValue(tripScheduleAdvanced.getReturnTrafficTypeId());
        tripScheduleAdvancedDTO.setReturnTrafficType(returnTrafficType);
        MainData deductionRules = new MainData();
        deductionRules.setValue(tripScheduleAdvanced.getDeductionRulesId());
        deductionRules.setLabel(tripScheduleAdvanced.getDeductionRulesName());
        tripScheduleAdvancedDTO.setDeductionRules(deductionRules);
        MainData collectionArea = new MainData();
        collectionArea.setValue(tripScheduleAdvanced.getCollectionAreaId());
        collectionArea.setLabel(tripScheduleAdvanced.getCollectionArea());
        tripScheduleAdvancedDTO.setCollectionArea(collectionArea);
        if (Objects.equals(tripScheduleAdvanced.getNeedTripConsumption(), 1)) {
            MainData consumption = new MainData();
            consumption.setValue(tripScheduleAdvanced.getConsumptionId());
            consumption.setLabel(tripScheduleAdvanced.getConsumptionName());
            tripScheduleAdvancedDTO.setConsumption(consumption);
        }
        return tripScheduleAdvancedDTO;
    }

    /**
     * 封装团期基本信息
     *
     * @param tripSchedule
     * @return
     */
    private TripScheduleBaseInfoDTO packTripScheduleBaseInfoDTOByTripSchedule(CustomizedTripSchedule tripSchedule) {
        TripScheduleBaseInfoDTO dto = EntityUtil.copy(tripSchedule, TripScheduleBaseInfoDTO.class);
        if (tripSchedule.getDepartureDate() != null) {
            //出发日期星期几
            String departureWeekDay = CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue());
            dto.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
            dto.setDepartureWeekDay(departureWeekDay);
        }
        MainData departurePlace = new MainData();
        departurePlace.setLabel(tripSchedule.getDeparturePlace());
        departurePlace.setValue(tripSchedule.getDeparturePlaceId());
        dto.setDeparturePlace(departurePlace);
        MainData destination = new MainData();
        destination.setLabel(tripSchedule.getDestination());
        destination.setValue(tripSchedule.getDestinationId());
        dto.setDestination(destination);
        MainData bigClient = new MainData();
        bigClient.setLabel(tripSchedule.getBigClientName());
        bigClient.setValue(tripSchedule.getBigClientId());
        dto.setBigClient(bigClient);
        MainData tourType = new MainData();
        tourType.setValue(tripSchedule.getTourTypeId());
        tourType.setLabel(tripSchedule.getTourTypeName());
        dto.setTourType(tourType);
        MainData groupType = new MainData();
        groupType.setLabel(tripSchedule.getGroupTypeName());
        groupType.setValue(tripSchedule.getGroupTypeId());
        dto.setGroupType(groupType);
        MainData groupNatureType = new MainData();
        groupNatureType.setValue(tripSchedule.getGroupNatureId());
        groupNatureType.setLabel(tripSchedule.getGroupNatureName());
        dto.setGroupNatureType(groupNatureType);
        return dto;
    }


    /**
     * 根据报价单获取销售设置信息
     *
     * @param quotationInfo
     * @return
     */
    private SalesSettingPackageInfoDTO getTripScheduleSalesSettingByQuatation(String quotationInfo) {
        //查询报价信息
        CustomizedQuotation quotation = quotationServiceImpl.getQuotationBaseInfo(quotationInfo);
        if (quotation == null) {
            return null;
        }
        SalesSettingPackageInfoDTO tripScheduleSalesSettingInfoDTO = new SalesSettingPackageInfoDTO();
        tripScheduleSalesSettingInfoDTO.setQuotationType(quotation.getQuotationType());
        //套餐总费用
        BigDecimal totalAmount = BigDecimal.ZERO;
        //总人数
        Integer peopleNum = 0;
        //总代收费用
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        //套餐
        if (quotation.getQuotationType().intValue() == NumberConstant.ONE.getValue()) {
            tripScheduleSalesSettingInfoDTO.setGroupFeeType(quotation.getGroupFeeType());
            //自由报价
            List<FreeQuoteReqPackageReq> reqPackageReqs = quotationServiceImpl.getQuotationEditFreePackageList(quotation.getId(), totalAmount);
            tripScheduleSalesSettingInfoDTO.setReqPackages(reqPackageReqs);
        } else {
            //行程报价
            List<TripQuoteReq> tripQuoteReqs = quotationServiceImpl.getQuotationEditTripQuoteList(quotation.getId(), totalAmount, peopleNum);
            tripScheduleSalesSettingInfoDTO.setTripQuoteReqs(tripQuoteReqs);
        }
        //旅客人数数组-行程报价套餐里面的旅客
        List<QuotationTouristTypeReq> touristTypes = quotationServiceImpl.getQuotationEditQuotationTouristTypeList(quotation.getId(), 1, null);
        tripScheduleSalesSettingInfoDTO.setTouristTypes(touristTypes);
        //代收费用
        List<CollectionFeeReq> collectionFees = quotationServiceImpl.getQuotationEditCollectionFeeList(quotation.getId(), totalCollectionFee);
        tripScheduleSalesSettingInfoDTO.setCollectionFees(collectionFees);
        tripScheduleSalesSettingInfoDTO.setTotalAmount(totalAmount);
        tripScheduleSalesSettingInfoDTO.setPeopleNum(peopleNum);
        tripScheduleSalesSettingInfoDTO.setTotalCollectionFee(totalCollectionFee);
        return tripScheduleSalesSettingInfoDTO;
    }


    /**
     * 根据团期id获取销售设置信息
     *
     * @param tripScheduleId
     * @return
     */
    private TripScheduleSalesSettingInfoDTO getTripScheduleSalesSettingByTripSchedule(Long tripScheduleId) {
        CustomizedTripSchedule tripSchedule = tripScheduleMapper.selectById(tripScheduleId);
        if (tripSchedule == null) {
            return null;
        }
        //套餐总费用
        BigDecimal totalAmount = BigDecimal.ZERO;
        //自由报价按服务-总单价
        BigDecimal totalSinglePrice = BigDecimal.ZERO;
        //总人数
        Integer peopleNum = 0;
        //总代收费用
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        //返回数据
        TripScheduleSalesSettingInfoDTO salesSettingInfoDTO = new TripScheduleSalesSettingInfoDTO();
        salesSettingInfoDTO.setQuotationNumber(tripSchedule.getQuotationNumber());
        //旅客剩余人数统计
        List<TripScheduleTouristCountDTO> touristCountList = tripScheduleTouristCountService.queryBySchedule(tripScheduleId);
        salesSettingInfoDTO.setTouristCountList(touristCountList);
        //报价方式
        salesSettingInfoDTO.setQuotationType(tripSchedule.getQuotationType());
        if (Objects.equals(tripSchedule.getQuotationType(), 1)) {
            salesSettingInfoDTO.setGroupFeeType(tripSchedule.getGroupFeeType());
        }
        if (tripSchedule.getMinDeposit() != null) {
            salesSettingInfoDTO.setMinDeposit(tripSchedule.getMinDeposit());
        }
        if (tripSchedule.getDeliveryDays() != null) {
            salesSettingInfoDTO.setDeliveryDays(tripSchedule.getDeliveryDays());
        }
        TripSchedulePackageJson packageJson = null;
        //查询自由报价套餐
        QueryWrapper<CustomizedTripScheduleFreeQuotePackage> packageWrapper = new QueryWrapper<>();
        packageWrapper.eq("schedule_id", tripScheduleId);
        packageWrapper.eq("is_deleted", 0);
        packageWrapper.orderByAsc("sort");
        List<CustomizedTripScheduleFreeQuotePackage> packageList = tripScheduleFreeQuotePackageMapper.selectList(packageWrapper);
        if (packageList != null && packageList.size() > 0) {
            //获取团期自由报价套餐列表
            packageJson = getTripScheduleFreePackageList(packageList, totalAmount, totalSinglePrice);
            salesSettingInfoDTO.setReqPackages(packageJson.getReqPackageReqs());
        } else {
            //查询行程报价
            QueryWrapper<CustomizedTripScheduleDate> dateWrapper = new QueryWrapper<>();
            dateWrapper.eq("schedule_id", tripSchedule.getId());
            dateWrapper.eq("is_deleted", 0);
            List<CustomizedTripScheduleDate> dates = tripScheduleDateMapper.selectList(dateWrapper);
            if (dates != null && dates.size() > 0) {
                System.out.println("行程报价 =====>>> " + dates.toString());
                //获取自由报价旅客类型列表
                List<QuotationTouristTypeReq> touristTypes = getTripScheduleTouristTypeList2(tripSchedule.getId());
                salesSettingInfoDTO.setTouristTypes(touristTypes);
                //获取团期自由报价套餐列表
                packageJson = getTripScheduleTripQuoteList(dates, totalAmount, peopleNum);
                salesSettingInfoDTO.setTripQuoteReqs(packageJson.getTripQuoteReqs());
            }
        }
        //查询代收费用
        CollectionJson collectionJson = getTripScheduleCollectionFeeList(tripScheduleId, totalCollectionFee);
        salesSettingInfoDTO.setCollectionFees(collectionJson.getCollectionFees());
        //查询增减团费
        List<FeeAdjustSaveDTO> feeAdjustSaveReqList = getTripScheduleFeeAdjustList(tripScheduleId);
        salesSettingInfoDTO.setFeeAdjustSaveReqList(feeAdjustSaveReqList);
        //金额统计
        if (packageJson != null) {
            salesSettingInfoDTO.setTotalAmount(packageJson.getTotalAmount());
            salesSettingInfoDTO.setPeopleNum(packageJson.getPeopleNum());
        }
        if (collectionJson != null) {
            salesSettingInfoDTO.setTotalCollectionFee(collectionJson.getTotalCollectionFee());
        }
        //获取线下渠道
        TripScheduleChannelDTO channelDTO = getTripScheduleChannel(tripScheduleId);
        if (channelDTO != null) {
            salesSettingInfoDTO.setChannelDTO(channelDTO);
        }
        return salesSettingInfoDTO;
    }

    /**
     * 获取线下渠道
     *
     * @param tripScheduleId
     * @return
     */
    private TripScheduleChannelDTO getTripScheduleChannel(Long tripScheduleId) {
        TripScheduleChannelDTO channelDTO = new TripScheduleChannelDTO();
        QueryWrapper<CustomizedTripScheduleChannel> channelWrapper = new QueryWrapper<>();
        channelWrapper.eq("schedule_id", tripScheduleId);
        channelWrapper.eq("is_deleted", 0);
        CustomizedTripScheduleChannel channel = tripScheduleChannelMapper.selectOne(channelWrapper);
        if (channel != null) {
            channelDTO.setId(channel.getId());
            channelDTO.setVisableType(channel.getVisableType());

            if (channel.getVisableType().intValue() == NumberConstant.THREE.getValue()) {
                //指定部门/人员
                QueryWrapper<CustomizedTripScheduleChannelDetail> detailWrapper = new QueryWrapper<>();
                detailWrapper.eq("channel_id", channel.getId());
                detailWrapper.eq("is_deleted", 0);
                List<CustomizedTripScheduleChannelDetail> detailList = tripScheduleChannelDetailMapper.selectList(detailWrapper);
                if (detailList != null && detailList.size() > 0) {
                    List<TripScheduleChannelDetailDTO> detailDTOList = new ArrayList<>();
                    for (CustomizedTripScheduleChannelDetail detail : detailList) {
                        TripScheduleChannelDetailDTO detailDTO = EntityUtil.copy(detail, TripScheduleChannelDetailDTO.class);
                        detailDTOList.add(detailDTO);
                    }
                    channelDTO.setDetailList(detailDTOList);
                }
            }else if (channel.getVisableType().intValue() == NumberConstant.TWO.getValue()) {
                //所有部门
                List<TripScheduleChannelDetailDTO> detailDTOList = new ArrayList<>();
                TripScheduleChannelDetailDTO detailDTO = new TripScheduleChannelDetailDTO();
                detailDTO.setAdjustType(channel.getAdjustType());
                detailDTO.setAmount(channel.getAmount());
                detailDTO.setPercent(channel.getPercent());
                detailDTOList.add(detailDTO);
                channelDTO.setDetailList(detailDTOList);
            }
            return channelDTO;
        }
        return null;
    }

    /**
     * 获取团期增减团费列表
     *
     * @param tripScheduleId
     * @return
     */
    private List<FeeAdjustSaveDTO> getTripScheduleFeeAdjustList(Long tripScheduleId) {
        List<FeeAdjustSaveDTO> feeAdjustSaveReqList = new ArrayList<>();
        QueryWrapper<CustomizedTripScheduleFeeAdjust> feeAdjustWrapper = new QueryWrapper<>();
        feeAdjustWrapper.eq("schedule_id", tripScheduleId);
        feeAdjustWrapper.eq("is_deleted", 0);
        feeAdjustWrapper.orderByAsc("gmt_create");
        List<CustomizedTripScheduleFeeAdjust> feeAdjustList = tripScheduleFeeAdjustMapper.selectList(feeAdjustWrapper);
        if (feeAdjustList != null) {
            for (CustomizedTripScheduleFeeAdjust feeAdjust : feeAdjustList) {
                FeeAdjustSaveDTO adjustSaveReq = EntityUtil.copy(feeAdjust, FeeAdjustSaveDTO.class);
                if (feeAdjust.getAdjustType() != null){
                    MainData adjustType = new MainData();
                    adjustType.setValue(feeAdjust.getAdjustType().longValue());
                    if (Objects.equals(feeAdjust.getAdjustType(),1)){
                        adjustType.setLabel("加錢");
                    }else{
                        adjustType.setLabel("退減");
                    }
                    adjustSaveReq.setAdjustType(adjustType);
                }
                Currency currency =  new Currency();
                currency.setText(feeAdjust.getCurrency());
                currency.setValue(feeAdjust.getCurrencyId());
                currency.setMarketExchangeRate(feeAdjust.getExchangeRate());
                adjustSaveReq.setCurrency(currency);
                feeAdjustSaveReqList.add(adjustSaveReq);
            }
        }
        return feeAdjustSaveReqList;
    }

    /**
     * 获取团期代收费用列表
     *
     * @param tripScheduleId
     * @param totalCollectionFee
     * @return
     */
    private CollectionJson getTripScheduleCollectionFeeList(Long tripScheduleId, BigDecimal totalCollectionFee) {
        CollectionJson collectionJson = new CollectionJson();
        List<CollectionFeeReq> collectionFees = new ArrayList<>();
        QueryWrapper<CustomizedTripScheduleCollectionFee> tripScheduleCollectionFeeWrapper = new QueryWrapper<>();
        tripScheduleCollectionFeeWrapper.eq("schedule_id", tripScheduleId);
        tripScheduleCollectionFeeWrapper.eq("is_deleted", 0);
        tripScheduleCollectionFeeWrapper.orderByAsc("gmt_create");
        List<CustomizedTripScheduleCollectionFee> collectionFeeList = tripScheduleCollectionFeeMapper.selectList(tripScheduleCollectionFeeWrapper);
        if (collectionFeeList != null) {
            for (CustomizedTripScheduleCollectionFee collectionFee : collectionFeeList) {
                CollectionFeeReq feeReq = EntityUtil.copy(collectionFee, CollectionFeeReq.class);
                MainData project = new MainData();
                project.setLabel(collectionFee.getProjectName());
                project.setValue(collectionFee.getMainDataId());
                feeReq.setProject(project);
                Currency currency = new Currency();
                currency.setValue(collectionFee.getCurrencyId());
                currency.setText(collectionFee.getCurrency());
                currency.setMarketExchangeRate(collectionFee.getExchangeRate());
                feeReq.setCurrency(currency);
                //旅客价格
                QueryWrapper<CustomizedTripScheduleCollectionTouristFee> collectionTouristFeeWrapper = new QueryWrapper<>();
                collectionTouristFeeWrapper.eq("collection_id", collectionFee.getId());
                List<CustomizedTripScheduleCollectionTouristFee> collectionTouristFees = tripScheduleCollectionTouristFeeMapper.selectList(collectionTouristFeeWrapper);
                if (collectionTouristFees != null && collectionTouristFees.size() > 0) {
                    List<CollectionTouristFeeReq> touristFees = new ArrayList<>();
                    for (CustomizedTripScheduleCollectionTouristFee collectionTouristFee : collectionTouristFees) {
                        if (collectionTouristFee.getTotalAmount() != null) {
                            totalCollectionFee = totalCollectionFee.add(collectionTouristFee.getTotalAmount());
                        }
                        CollectionTouristFeeReq touristFeeReq = new CollectionTouristFeeReq();
                        touristFeeReq.setCurrencyId(collectionTouristFee.getCurrencyId());
                        touristFeeReq.setCurrencyName(collectionTouristFee.getCurrency());
                        touristFeeReq.setExchangeRate(collectionTouristFee.getExchangeRate());
                        touristFeeReq.setTouristTypeName(collectionTouristFee.getTouristTypeName());
                        touristFeeReq.setTouristTypeId(collectionTouristFee.getTouristTypeId());
                        touristFeeReq.setAmount(collectionTouristFee.getTotalAmount());
                        touristFees.add(touristFeeReq);
                    }
                    feeReq.setTouristFees(touristFees);
                }
                collectionFees.add(feeReq);
            }
            collectionJson.setCollectionFees(collectionFees);
            collectionJson.setTotalCollectionFee(totalCollectionFee);
        }
        return collectionJson;
    }

    /**
     * 获取团期行程报价套餐列表
     *
     * @param dates       行程报价套餐列表
     * @param totalAmount 套餐总金额
     * @param peopleNum   套餐总人数
     * @return
     */
    private TripSchedulePackageJson getTripScheduleTripQuoteList(List<CustomizedTripScheduleDate> dates, BigDecimal totalAmount, Integer peopleNum) {
        TripSchedulePackageJson json = new TripSchedulePackageJson();
        List<TripQuoteReq> tripQuoteReqs = new ArrayList<>();
        for (CustomizedTripScheduleDate date : dates) {
            if (date.getTotalAmount() != null) {
                totalAmount = totalAmount.add(date.getTotalAmount());
            }
            if (date.getTotalPeople() != null) {
                peopleNum = peopleNum + date.getTotalPeople();
            }
            TripQuoteReq quoteReq = EntityUtil.copy(date, TripQuoteReq.class);
            Currency currency = new Currency();
            currency.setValue(date.getCurrencyId());
            currency.setText(date.getCurrency());
            currency.setMarketExchangeRate(date.getExchangeRate());
            quoteReq.setCurrency(currency);
            //服务项目
            QueryWrapper<CustomizedTripScheduleQuoteServiceItems> quoteServiceItemsWrapper = new QueryWrapper<>();
            quoteServiceItemsWrapper.eq("date_id", date.getId());
            quoteServiceItemsWrapper.eq("is_deleted", 0);
            List<CustomizedTripScheduleQuoteServiceItems> quoteServiceItemsList = tripScheduleQuoteServiceItemsMapper.selectList(quoteServiceItemsWrapper);
            if (quoteServiceItemsList != null && quoteServiceItemsList.size() > 0) {
                System.out.println("行程报价item =====>>> " + quoteServiceItemsList.toString());
                List<TripQuoteServiceItemsReq> serviceItems = new ArrayList<>();
                for (CustomizedTripScheduleQuoteServiceItems quoteServiceItem : quoteServiceItemsList) {
                    TripQuoteServiceItemsReq itemsReq = EntityUtil.copy(quoteServiceItem, TripQuoteServiceItemsReq.class);
                    MainData serviceType = new MainData();
                    serviceType.setValue(quoteServiceItem.getMainDataId());
                    serviceType.setLabel(quoteServiceItem.getServiceTypeName());
                    itemsReq.setServiceType(serviceType);
                    itemsReq.setProjectName(quoteServiceItem.getName());
                    itemsReq.setAmount(quoteServiceItem.getTotalNum());
                    serviceItems.add(itemsReq);
                }
                quoteReq.setServiceItems(serviceItems);
            }
            tripQuoteReqs.add(quoteReq);
        }
        json.setTripQuoteReqs(tripQuoteReqs);
        json.setTotalAmount(totalAmount);
        json.setPeopleNum(peopleNum);
        return json;
    }

    /**
     * 获取自由报价旅客类型列表
     *
     * @param scheduleId
     * @return
     */
    private List<QuotationTouristTypeReq> getTripScheduleTouristTypeList(Long scheduleId) {
        List<QuotationTouristTypeReq> touristTypes = new ArrayList<>();
        //旅客人数
        touristTypes = quotationTouristTypeMapper.queryRemainPeople(scheduleId);
        /*QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
        touristTypeWrapper.eq("schedule_id",scheduleId);
        touristTypeWrapper.eq("is_deleted",0);
        touristTypeWrapper.orderByAsc("sort");
        List<CustomizedQuotationTouristType> touristTypeList = quotationTouristTypeMapper.selectList(touristTypeWrapper);
        if (touristTypeList != null && touristTypeList.size() > 0){
            for (CustomizedQuotationTouristType touristType : touristTypeList){
                QuotationTouristTypeReq touristTypeReq = EntityUtil.copy(touristType, QuotationTouristTypeReq.class);
                touristTypeReq.setValue(touristType.getMainDataId());
                touristTypeReq.setLabel(touristType.getName());
                touristTypes.add(touristTypeReq);
            }
        }*/
        return touristTypes;
    }

    /**
     * 获取自由报价旅客类型列表
     *
     * @param scheduleId
     * @return
     */
    private List<QuotationTouristTypeReq> getTripScheduleTouristTypeList2(Long scheduleId) {
        List<QuotationTouristTypeReq> touristTypes = new ArrayList<>();
        //旅客人数
        touristTypes = quotationTouristTypeMapper.queryRemainPeople2(scheduleId);
        return touristTypes;
    }

    /**
     * 获取团期自由报价套餐列表
     *
     * @param packageList
     * @param totalAmount
     * @param totalSinglePrice
     * @return
     */
    private TripSchedulePackageJson getTripScheduleFreePackageList(List<CustomizedTripScheduleFreeQuotePackage> packageList, BigDecimal totalAmount, BigDecimal totalSinglePrice) {
        TripSchedulePackageJson packageJson = new TripSchedulePackageJson();
        List<FreeQuoteReqPackageReq> reqPackages = new ArrayList<>();
        for (CustomizedTripScheduleFreeQuotePackage freeQuotePackage : packageList) {
            if (freeQuotePackage.getTotalAmount() != null) {
                totalAmount = totalAmount.add(freeQuotePackage.getTotalAmount());
            }
            FreeQuoteReqPackageReq packageReq = EntityUtil.copy(freeQuotePackage, FreeQuoteReqPackageReq.class);
            Currency currency = new Currency();
            currency.setText(freeQuotePackage.getCurrency());
            currency.setValue(freeQuotePackage.getCurrencyId());
            currency.setMarketExchangeRate(freeQuotePackage.getExchangeRate());
            packageReq.setCurrency(currency);
            packageReq.setPackageName(freeQuotePackage.getName());
            List<QuotationTouristTypeReq> packageTouristTypes = quotationTouristTypeMapper.queryPackageToutistType(freeQuotePackage.getScheduleId(), freeQuotePackage.getId());
            packageReq.setPackageTouristTypes(packageTouristTypes);
            //获取服务项目旅客类型列表(预订下单页面)
            List<QuotationTouristTypeDTO> touristTypeDTOList = tripScheduleTouristPriceMapper.queryListByPackage(freeQuotePackage.getId(), freeQuotePackage.getScheduleId());
            packageReq.setQuotationTouristTypeDTOS(touristTypeDTOList);
            //服务项目
            QueryWrapper<CustomizedTripSchedulePackageServiceItems> serviceItemsWrapper = new QueryWrapper<>();
            serviceItemsWrapper.eq("package_id", freeQuotePackage.getId());
            serviceItemsWrapper.eq("is_deleted", 0);
            List<CustomizedTripSchedulePackageServiceItems> packageServiceItems = tripSchedulePackageServiceItemsMapper.selectList(serviceItemsWrapper);
            if (packageServiceItems != null && packageServiceItems.size() > 0) {
                List<FreeQuoteServiceItemsReq> serviceItemsReqs = new ArrayList<>();
                for (CustomizedTripSchedulePackageServiceItems serviceItems : packageServiceItems) {
                    if (serviceItems.getSinglePrice() != null) {
                        totalSinglePrice = totalSinglePrice.add(serviceItems.getSinglePrice());
                    }
                    FreeQuoteServiceItemsReq serviceItemsReq = EntityUtil.copy(serviceItems, FreeQuoteServiceItemsReq.class);
                    MainData serviceType = new MainData();
                    serviceType.setLabel(serviceItems.getServiceTypeName());
                    serviceType.setValue(serviceItems.getMainDataId());
                    serviceItemsReq.setServiceType(serviceType);
                    serviceItemsReq.setProjectName(serviceItems.getName());
                    QueryWrapper<CustomizedTripScheduleTouristPrice> touristPriceWrapper = new QueryWrapper<>();
                    touristPriceWrapper.eq("service_item_id", serviceItems.getId());
                    List<CustomizedTripScheduleTouristPrice> touristPriceList = tripScheduleTouristPriceMapper.selectList(touristPriceWrapper);
                    if (touristPriceList != null && touristPriceList.size() > 0) {
                        List<TouristPriceReq> touristPriceReqs = new ArrayList<>();
                        for (CustomizedTripScheduleTouristPrice touristPrice : touristPriceList) {
                            TouristPriceReq touristPriceReq = EntityUtil.copy(touristPrice, TouristPriceReq.class);
                            touristPriceReq.setTouristTypeId(touristPrice.getMainDataId());
                            touristPriceReq.setPrice(touristPrice.getTotalPrice());
                            touristPriceReqs.add(touristPriceReq);
                        }
                        serviceItemsReq.setTouristPriceReqs(touristPriceReqs);
                    }
                    serviceItemsReqs.add(serviceItemsReq);
                }
                packageReq.setServiceItemsReqs(serviceItemsReqs);
            }
            reqPackages.add(packageReq);
        }
        packageJson.setReqPackageReqs(reqPackages);
        packageJson.setTotalAmount(totalAmount);
        packageJson.setTotalSinglePrice(totalSinglePrice);
        return packageJson;
    }


    /**
     * 获取联络人信息和旅客信息
     *
     * @param tripSchedule
     * @param orderPageInfoDTO
     * @return
     */
    private ScheduleOrderPageInfoDTO saveContactAndTouristInfo(CustomizedTripSchedule tripSchedule, ScheduleOrderPageInfoDTO orderPageInfoDTO) {
        //是否关联询价单
        if (tripSchedule.getInquiryId() != null) {
            CustomizedInquiry inquiry = inquiryMapper.selectById(tripSchedule.getInquiryId());
            if (inquiry != null) {
                orderPageInfoDTO.setCustomerType(inquiry.getCustomerType());
                ContactReq contactReq = new ContactReq();
                contactReq.setContactEnName(inquiry.getContactEnName());
                contactReq.setContactEnSurname(inquiry.getContactEnSurname());
                contactReq.setContactCnSurname(inquiry.getContactCnSurname());
                contactReq.setContactCnName(inquiry.getContactCnName());
                orderPageInfoDTO.setContactReq(contactReq);
                orderPageInfoDTO.setContactGender(inquiry.getContactGender());
                orderPageInfoDTO.setContactTelephones(inquiry.getContactTelephones());
                orderPageInfoDTO.setContactEmail(inquiry.getContactEmail());
                orderPageInfoDTO.setInternalRemark(inquiry.getInternalRemark());
            }
        } else {
            //是否关联报价单
            if (tripSchedule.getQuotationId() != null) {
                CustomizedQuotation quotation = quotationMapper.selectById(tripSchedule.getQuotationId());
                if (quotation != null) {
                    orderPageInfoDTO.setCustomerType(quotation.getCustomerType());
                    ContactReq contactReq = new ContactReq();
                    contactReq.setContactEnName(quotation.getContactEnName());
                    contactReq.setContactEnSurname(quotation.getContactEnSurname());
                    contactReq.setContactCnSurname(quotation.getContactCnSurname());
                    contactReq.setContactCnName(quotation.getContactCnName());
                    orderPageInfoDTO.setContactReq(contactReq);
                    orderPageInfoDTO.setContactGender(quotation.getContactGender());
                    orderPageInfoDTO.setContactTelephones(quotation.getContactTelephones());
                    orderPageInfoDTO.setContactEmail(quotation.getContactEmail());
                    orderPageInfoDTO.setInternalRemark(quotation.getInternalRemark());
                }
            }
        }
        return orderPageInfoDTO;
    }


    /**
     * 团期详情 - 获取团期档案列表
     *
     * @param pdfUrl
     * @param scheduleId
     * @return
     */
    private List<ArchivesJson> getArchivesList(String pdfUrl, Long scheduleId) {
        List<ArchivesJson> archivesList = new ArrayList<>();
        if (StringUtils.isNotBlank(pdfUrl)) {
            //生成档案记录
            ArchivesJson archives = saveArchivesJson(pdfUrl);
            archivesList.add(archives);
        }
        //根据团期获取签证详情
        VisaDTO visaDTO = tripScheduleVisaMapper.queryFilesJsonBySchedule(scheduleId);
        if (visaDTO != null) {
            String filesJson = visaDTO.getFilesJson();
            if (StringUtils.isNotBlank(filesJson)) {
                //生成档案记录
                ArchivesJson archives = saveArchivesJson(filesJson);
                archivesList.add(archives);
            }
        }
        return archivesList;
    }

    /**
     * 生成档案记录
     *
     * @param jsonStr
     * @return
     */
    private ArchivesJson saveArchivesJson(String jsonStr) {
        JSONObject json = JSON.parseObject(jsonStr);
        ArchivesJson archives = new ArchivesJson();
        archives.setFileTitle(json.getString("fileName"));
        archives.setFileUrl(json.getString("fileUrl"));
        archives.setGmtCreate((LocalDateTime) json.get("createTime"));
        Long createId = json.getLong("createBy");
        if (createId != null) {
            UserDTO userDTO = sysUserService.loadUserByParam(createId, 1);
            if (userDTO != null) {
                archives.setCreator(StrUtil.concat(true, userDTO.getFullName(), "/", userDTO.getDept()));
            }
        }
        return archives;
    }

    /**
     * 保存增減團費設置
     *
     * @param req
     * @param userId
     */
    private void saveTripScheduleFeeAdjust(SaveTripScheduleSalesSettingReq req, Long userId) {
        List<FeeAdjustSaveReq> feeAdjustSaveReqList = req.getFeeAdjustSaveReqList();
        if (feeAdjustSaveReqList != null && feeAdjustSaveReqList.size() > 0) {
            //清空旧数据
            tripScheduleFeeAdjustMapper.cleanBySchedule(req.getScheduleId(), userId);
            //总费用
            BigDecimal totalFee = BigDecimal.ZERO;
            List<CustomizedTripScheduleFeeAdjust> feeAdjustList = new ArrayList<>();
            for (FeeAdjustSaveReq saveReq : feeAdjustSaveReqList) {
                CustomizedTripScheduleFeeAdjust feeAdjust = EntityUtil.copy(saveReq, CustomizedTripScheduleFeeAdjust.class);
                feeAdjust.setId(SnowflakeIdWorker.nextId());
                MainDataFieldDataDTO proDTO = mainDataFieldDataService.queryFieldData(saveReq.getMainDataId());
                if (proDTO != null) {
                    feeAdjust.setProjectName(proDTO.getFieldValue());
                }
                feeAdjust.setScheduleId(req.getScheduleId());
                feeAdjust.setCurrencyId(saveReq.getCurrency().getValue());
                feeAdjust.setCurrency(saveReq.getCurrency().getText());
                feeAdjust.setExchangeRate(saveReq.getCurrency().getMarketExchangeRate());
                feeAdjust.setCreateId(userId);
                feeAdjust.setGmtCreate(LocalDateTime.now());
                feeAdjust.setIsDeleted(0);
                feeAdjustList.add(feeAdjust);
                //计算费用
                totalFee = totalFee.add(saveReq.getCostAmount());
            }
            Integer batch = tripScheduleFeeAdjustMapper.insertBatchSomeColumn(feeAdjustList);
            if (batch < feeAdjustList.size()) {
                throw new BusinessException(SystemError.SYS_437);
            }
            //团期金额统计
            CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(req.getScheduleId());
            if (amountStatistics != null) {
                amountStatistics.setAdjustFee(totalFee);
                amountStatistics.setModifiedId(userId);
                int update = tripScheduleAmountStatisticsMapper.updateById(amountStatistics);
                if (update <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
    }

    /**
     * 保存代收费用
     *
     * @param req
     * @param userId
     */
    private void saveTripScheduleCollectionFee(SaveTripScheduleSalesSettingReq req, Long userId) {
        List<CollectionFeeReq> collectionFees = req.getCollectionFees();
        if (collectionFees != null && collectionFees.size() > 0) {
            //总代收费用
            BigDecimal totalCollectionFee = BigDecimal.ZERO;
            //清除旧数据
            tripScheduleCollectionFeeMapper.cleanBySchedule(req.getScheduleId(), userId);
            //新增代收费用
            for (CollectionFeeReq saveReq : collectionFees) {
                CustomizedTripScheduleCollectionFee collectionFee = EntityUtil.copy(saveReq, CustomizedTripScheduleCollectionFee.class);
                collectionFee.setId(SnowflakeIdWorker.nextId());
                MainData project = saveReq.getProject();
                collectionFee.setMainDataId(project.getValue());
                collectionFee.setProjectName(project.getLabel());
                collectionFee.setScheduleId(req.getScheduleId());
                collectionFee.setCurrencyId(saveReq.getCurrency().getValue());
                collectionFee.setCurrency(saveReq.getCurrency().getText());
                collectionFee.setExchangeRate(saveReq.getCurrency().getMarketExchangeRate());
                collectionFee.setCreateId(userId);
                collectionFee.setGmtCreate(LocalDateTime.now());
                collectionFee.setIsDeleted(0);
                int save = tripScheduleCollectionFeeMapper.insert(collectionFee);
                if (save < 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
                List<CollectionTouristFeeReq> touristFees = saveReq.getTouristFees();
                //代收费用旅客类型价格
                if (touristFees != null && touristFees.size() > 0) {
                    List<CustomizedTripScheduleCollectionTouristFee> collectionFeeList = new ArrayList<>();
                    for (CollectionTouristFeeReq touristFeeSaveReq : touristFees) {
                        //过滤多余的旅客类型代收费用
                        for (QuotationTouristTypeReq touristTypeReq : req.getTouristTypes()) {
                            if (Objects.equals(touristFeeSaveReq.getTouristTypeId(), touristTypeReq.getValue())) {
                                CustomizedTripScheduleCollectionTouristFee collectionTouristFee = EntityUtil.copy(touristFeeSaveReq, CustomizedTripScheduleCollectionTouristFee.class);
                                collectionTouristFee.setId(SnowflakeIdWorker.nextId());
                                collectionTouristFee.setTouristTypeId(touristFeeSaveReq.getTouristTypeId());
                                collectionTouristFee.setTotalAmount(touristFeeSaveReq.getAmount());
                                collectionTouristFee.setTouristTypeName(touristFeeSaveReq.getTouristTypeName());
                                collectionTouristFee.setCurrencyId(touristFeeSaveReq.getCurrencyId());
                                collectionTouristFee.setCurrency(touristFeeSaveReq.getCurrencyName());
                                collectionTouristFee.setExchangeRate(touristFeeSaveReq.getExchangeRate());
                                collectionTouristFee.setScheduleId(req.getScheduleId());
                                collectionTouristFee.setCollectionId(collectionFee.getId());
                                collectionFeeList.add(collectionTouristFee);
                                //计算总费用
                                totalCollectionFee = totalCollectionFee.add(touristFeeSaveReq.getAmount());
                                break;
                            }
                        }
                    }
                    Integer batch = tripScheduleCollectionTouristFeeMapper.insertBatchSomeColumn(collectionFeeList);
                    if (batch < collectionFeeList.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
            }
            //团期金额统计
            CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(req.getScheduleId());
            if (amountStatistics != null) {
                amountStatistics.setCollectionFee(totalCollectionFee);
                amountStatistics.setModifiedId(userId);
                int update = tripScheduleAmountStatisticsMapper.updateById(amountStatistics);
                if (update <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
    }

    /**
     * 保存套餐信息
     *
     * @param req
     * @param userId
     */
    private void saveTripSchedulePackage(SaveTripScheduleSalesSettingReq req, Long userId) {
        //先清空旧数据（包含团期旅客类型和套餐旅客类型）
        quotationTouristTypeMapper.cleanBySchedule(req.getScheduleId(), userId);

        //清空行程报价套餐
        tripScheduleDateMapper.clearBySchedule(req.getScheduleId(), userId);
        //清空服务项目
        tripScheduleQuoteServiceItemsMapper.cleanBySchedule(req.getScheduleId(), userId);

        //清空自由报价套餐旧数据
        tripScheduleFreeQuotePackageMapper.clearBySchedule(req.getScheduleId(), userId);
        //清空团期服务项目旧数据
        tripSchedulePackageServiceItemsMapper.cleanBySchedule(req.getScheduleId(), userId);

        //总人数
        int totalPeople = 0;
        //总团费
        BigDecimal totalGroupFee = BigDecimal.ZERO;
        if (Objects.equals(req.getQuotationType(), 1)) {
            //自由报价
            List<FreeQuoteReqPackageReq> reqPackages = req.getReqPackages();
            //第一个套餐旅客类型（套餐旅客类型主数据ID与团期旅客类型主数据ID一致）
            List<QuotationTouristTypeReq> touristTypeList = reqPackages.get(0).getPackageTouristTypes();
            List<QuotationTouristTypeReq> touristTypeList2 = new ArrayList<>();
            //查询统计团期旅客类型人数
            for (int i = 0; i < touristTypeList.size(); i++) {
                QuotationTouristTypeReq typeReq1 = touristTypeList.get(i);
                QuotationTouristTypeReq typeReq2 = EntityUtil.copy(typeReq1, QuotationTouristTypeReq.class);
                Integer touristNumber = 0;
                //遍历所有套餐
                for (FreeQuoteReqPackageReq reqPackageReq : reqPackages) {
                    //套餐旅客类型
                    List<QuotationTouristTypeReq> packageTouristTypes = reqPackageReq.getPackageTouristTypes();
                    for (QuotationTouristTypeReq touristTypeReq : packageTouristTypes) {
                        //按旅客类型主数据ID分类
                        if (typeReq2.getValue().longValue() == touristTypeReq.getValue().longValue()) {
                            if (i == 0) {
                                touristNumber = touristTypeReq.getPeopleNum();
                            } else {
                                touristNumber += touristTypeReq.getPeopleNum();
                            }
                        }
                    }
                }
                //统计团期总人数
                totalPeople += touristNumber;
                typeReq2.setPeopleNum(touristNumber);
                touristTypeList2.add(typeReq2);
            }
            //团期金额统计
            CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(req.getScheduleId());
            if (amountStatistics != null) {
                //团期总人数校验拦截（不能小于已下单人数）
                if (amountStatistics.getOrderPeople().intValue() > totalPeople) {
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4033);
                }
            }
            //保存团期旅客统计（该数据自由报价前端没有传，需自己统计）
            req.setTouristTypes(touristTypeList2);
            //保存团期旅客人数
            //新增团期旅客类型
            List<CustomizedQuotationTouristType> addList = new ArrayList<>();
            for (QuotationTouristTypeReq touristTypeReq : touristTypeList) {
                CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setScheduleId(req.getScheduleId());
                quotationTouristType.setMainDataId(touristTypeReq.getValue());
                quotationTouristType.setName(touristTypeReq.getLabel());
                quotationTouristType.setAgeBegin(touristTypeReq.getAgeBegin());
                quotationTouristType.setAgeEnd(touristTypeReq.getAgeEnd());
                quotationTouristType.setPeopleNum(touristTypeReq.getPeopleNum());
                quotationTouristType.setCreateId(userId);
                quotationTouristType.setIsDeleted(0);
                addList.add(quotationTouristType);
            }
            //批量新增团期旅客类型
            if (addList.size() > 0) {
                Integer batchAdd = quotationTouristTypeMapper.insertBatchSomeColumn(addList);
                if (batchAdd < addList.size()) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
            for (FreeQuoteReqPackageReq freePkg : reqPackages) {
                //新增旅客类型列表
                List<CustomizedQuotationTouristType> pkgTouristTypeList = new ArrayList<>();
                CustomizedTripScheduleFreeQuotePackage freeQuotePackage = EntityUtil.copy(freePkg, CustomizedTripScheduleFreeQuotePackage.class);
                freeQuotePackage.setId(SnowflakeIdWorker.nextId());
                freeQuotePackage.setScheduleId(req.getScheduleId());
                freeQuotePackage.setName(freePkg.getPackageName());
                freeQuotePackage.setCurrencyId(freePkg.getCurrency().getValue());
                freeQuotePackage.setCurrency(freePkg.getCurrency().getText());
                freeQuotePackage.setExchangeRate(freePkg.getCurrency().getMarketExchangeRate());
                freeQuotePackage.setCreateId(userId);
                freeQuotePackage.setGmtCreate(LocalDateTime.now());
                freeQuotePackage.setIsDeleted(0);
                //清空服务项目旅客价格
                QueryWrapper<CustomizedTripScheduleTouristPrice> touristPriceWrapper = new QueryWrapper<>();
                touristPriceWrapper.eq("package_id", freeQuotePackage.getId());
                tripScheduleTouristPriceMapper.delete(touristPriceWrapper);
                //套餐旅客类型
                List<QuotationTouristTypeReq> packageTouristTypes = freePkg.getPackageTouristTypes();
                if (packageTouristTypes != null && packageTouristTypes.size() > 0) {
                    for (QuotationTouristTypeReq touristTypeReq : packageTouristTypes) {
                        //新增旅客类型
                        CustomizedQuotationTouristType pkgTouristType = new CustomizedQuotationTouristType();
                        pkgTouristType.setId(SnowflakeIdWorker.nextId());
                        pkgTouristType.setPackageId(freeQuotePackage.getId());
                        //    pkgTouristType.setScheduleId(req.getScheduleId());
                        pkgTouristType.setName(touristTypeReq.getLabel());
                        pkgTouristType.setMainDataId(touristTypeReq.getValue());
                        pkgTouristType.setAgeEnd(touristTypeReq.getAgeEnd());
                        pkgTouristType.setAgeBegin(touristTypeReq.getAgeBegin());
                        pkgTouristType.setPeopleNum(touristTypeReq.getPeopleNum());
                        pkgTouristType.setCreateId(userId);
                        pkgTouristType.setIsDeleted(0);
                        pkgTouristTypeList.add(pkgTouristType);
                    }
                    //批量新增套餐旅客类型
                    Integer addPkgTouristType = quotationTouristTypeMapper.insertBatchSomeColumn(pkgTouristTypeList);
                    if (addPkgTouristType < pkgTouristTypeList.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
                //套餐总金额
                BigDecimal totalAmount = BigDecimal.ZERO;
                //套餐总人数
                int pkgPeopleNum = 0;
                //新增套餐
                int save = tripScheduleFreeQuotePackageMapper.insert(freeQuotePackage);
                if (save <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
                List<QuotationTouristTypeReq> touristTypes = freePkg.getPackageTouristTypes();
                //服务项目
                if (freePkg.getServiceItemsReqs() != null && freePkg.getServiceItemsReqs().size() > 0) {
                    //新增套餐服务项目
                    List<CustomizedTripSchedulePackageServiceItems> packageServiceItemsList = new ArrayList<>();
                    for (FreeQuoteServiceItemsReq serviceItemsReq : freePkg.getServiceItemsReqs()) {
                        BigDecimal itemTotalAmount = BigDecimal.ZERO;
                        Integer itemPeopleNum = 0;
                        for (QuotationTouristTypeReq touristTypeReq : touristTypes) {
                            pkgPeopleNum += touristTypeReq.getPeopleNum();
                            itemPeopleNum += touristTypeReq.getPeopleNum();
                        }
                        CustomizedTripSchedulePackageServiceItems packageServiceItems = EntityUtil.copy(serviceItemsReq, CustomizedTripSchedulePackageServiceItems.class);
                        packageServiceItems.setId(SnowflakeIdWorker.nextId());
                        packageServiceItems.setPackageId(freeQuotePackage.getId());
                        packageServiceItems.setScheduleId(req.getScheduleId());
                        packageServiceItems.setGroupFeeType(req.getGroupFeeType());
                        packageServiceItems.setMainDataId(serviceItemsReq.getServiceType().getValue());
                        packageServiceItems.setServiceTypeName(serviceItemsReq.getServiceType().getLabel());
                        packageServiceItems.setName(serviceItemsReq.getProjectName());
                        packageServiceItems.setCreateId(userId);
                        packageServiceItems.setGmtCreate(LocalDateTime.now());
                        packageServiceItems.setIsDeleted(0);
                        //旅客价格list
                        List<CustomizedTripScheduleTouristPrice> touristPriceList = new ArrayList<>();
                        if (req.getGroupFeeType().intValue() == NumberConstant.ONE.getValue()) {
                            //按人均报价
                            List<TouristPriceReq> touristPriceReqs = serviceItemsReq.getTouristPriceReqs();
                            if (touristPriceReqs != null && touristPriceReqs.size() > 0) {
                                BigDecimal totalPrice = BigDecimal.ZERO;
                                for (TouristPriceReq priceReq : touristPriceReqs) {
                                    //新增旅客价格
                                    CustomizedTripScheduleTouristPrice touristPrice = EntityUtil.copy(priceReq, CustomizedTripScheduleTouristPrice.class);
                                    touristPrice.setId(SnowflakeIdWorker.nextId());
                                    touristPrice.setMainDataId(priceReq.getTouristTypeId());
                                    //查询套餐旅客类型ID
                                    CustomizedQuotationTouristType itemTouristType = quotationTouristTypeMapper.queryByServiceItem(
                                            req.getScheduleId(), freeQuotePackage.getId(), priceReq.getTouristTypeId());
                                    touristPrice.setTouristTypeId(itemTouristType.getId());
                                    touristPrice.setTotalPrice(priceReq.getPrice());
                                    touristPrice.setPackageId(freeQuotePackage.getId());
                                    touristPrice.setServiceItemId(packageServiceItems.getId());
                                    touristPrice.setGmtCreate(LocalDateTime.now());
                                    touristPrice.setCreateId(userId);
                                    touristPriceList.add(touristPrice);
                                    for (QuotationTouristTypeReq touristTypeReq : touristTypes) {
                                        //团期旅客类型统计
                                        CustomizedTripScheduleTouristCount touristCount = tripScheduleTouristCountMapper.queryByTourist(touristTypeReq.getValue(), req.getScheduleId());
                                        if (touristCount == null) {
                                            //新增操作
                                            touristCount = new CustomizedTripScheduleTouristCount();
                                            touristCount.setId(SnowflakeIdWorker.nextId());
                                            touristCount.setScheduleId(req.getScheduleId());
                                            touristCount.setTouristTypeId(touristTypeReq.getValue());
                                            touristCount.setTouristTypeName(touristTypeReq.getLabel());
                                            touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                                            touristCount.setOrderPeople(0);
                                            touristCount.setCreateId(userId);
                                            touristCount.setIsDeleted(0);
                                            int insertCount = tripScheduleTouristCountMapper.insert(touristCount);
                                            if (insertCount <= 0) {
                                                throw new BusinessException(SystemError.SYS_437);
                                            }
                                        } else {
                                            //修改操作
                                            if (touristCount.getTotalPeople().intValue() != touristTypeReq.getPeopleNum().intValue()) {
                                                if (touristCount.getOrderPeople().intValue() > touristTypeReq.getPeopleNum()) {
                                                    throw new BusinessException(SystemError.CUSTOM_ORDER_4031, touristTypeReq.getLabel());
                                                }
                                                touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                                                touristCount.setModifiedId(userId);
                                                int updateCount = tripScheduleTouristCountMapper.updateById(touristCount);
                                                if (updateCount <= 0) {
                                                    throw new BusinessException(SystemError.SYS_437);
                                                }
                                            }
                                        }
                                        //统计金额
                                        if (priceReq.getTouristTypeId().longValue() == touristTypeReq.getValue().longValue()) {
                                            totalPrice = totalPrice.add(priceReq.getPrice().multiply(new BigDecimal(touristTypeReq.getPeopleNum())));
                                            break;
                                        }
                                    }
                                }
                                //批量新增旅客价格
                                Integer batch = tripScheduleTouristPriceMapper.insertBatchSomeColumn(touristPriceList);
                                if (batch < touristPriceList.size()) {
                                    throw new BusinessException(SystemError.SYS_437);
                                }
                                totalAmount = totalAmount.add(totalPrice);
                                itemTotalAmount = itemTotalAmount.add(totalPrice);
                                packageServiceItems.setTotalPrice(totalPrice);
                                packageServiceItems.setTotalPrice(itemTotalAmount);
                                packageServiceItems.setTotalNum(itemPeopleNum);
                                //计算服务项目单价
                                if (itemPeopleNum == 0) {
                                    //处理人数为0的情况
                                    packageServiceItems.setSinglePrice(BigDecimal.ZERO);
                                } else {
                                    packageServiceItems.setSinglePrice(itemTotalAmount.divide(new BigDecimal(itemPeopleNum), 2, BigDecimal.ROUND_HALF_UP));
                                }
                            }
                        } else {
                            //按服务项报价
                            BigDecimal totalPrice = serviceItemsReq.getSinglePrice().multiply(new BigDecimal(serviceItemsReq.getTotalNum()));
                            totalAmount = totalAmount.add(totalPrice);
                            packageServiceItems.setTotalPrice(totalPrice);
                            packageServiceItems.setSinglePrice(serviceItemsReq.getSinglePrice());
                            //套餐旅客价格
                            for (QuotationTouristTypeReq touristTypeReq : touristTypeList) {
                                CustomizedTripScheduleTouristPrice touristPrice = EntityUtil.copy(touristTypeReq, CustomizedTripScheduleTouristPrice.class);
                                touristPrice.setId(SnowflakeIdWorker.nextId());
                                touristPrice.setMainDataId(touristTypeReq.getValue());
                                touristPrice.setTouristTypeName(touristTypeReq.getLabel());
                                //查询套餐旅客类型ID
                                CustomizedQuotationTouristType itemTouristType = quotationTouristTypeMapper.queryByServiceItem(
                                        req.getScheduleId(), freeQuotePackage.getId(), touristTypeReq.getValue());
                                touristPrice.setTouristTypeId(itemTouristType.getId());
                                touristPrice.setTotalPrice(serviceItemsReq.getSinglePrice());
                                touristPrice.setPackageId(freeQuotePackage.getId());
                                touristPrice.setServiceItemId(packageServiceItems.getId());
                                touristPrice.setGmtCreate(LocalDateTime.now());
                                touristPrice.setCreateId(userId);
                                touristPriceList.add(touristPrice);
                                //团期旅客类型统计
                                CustomizedTripScheduleTouristCount touristCount = tripScheduleTouristCountMapper.queryByTourist(touristTypeReq.getValue(), req.getScheduleId());
                                if (touristCount == null) {
                                    //新增操作
                                    touristCount = new CustomizedTripScheduleTouristCount();
                                    touristCount.setId(SnowflakeIdWorker.nextId());
                                    touristCount.setScheduleId(req.getScheduleId());
                                    touristCount.setTouristTypeId(touristTypeReq.getValue());
                                    touristCount.setTouristTypeName(touristTypeReq.getLabel());
                                    touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                                    touristCount.setOrderPeople(0);
                                    touristCount.setCreateId(userId);
                                    touristCount.setIsDeleted(0);
                                    int insertCount = tripScheduleTouristCountMapper.insert(touristCount);
                                    if (insertCount <= 0) {
                                        throw new BusinessException(SystemError.SYS_437);
                                    }
                                } else {
                                    //修改操作
                                    if (touristCount.getTotalPeople().intValue() != touristTypeReq.getPeopleNum().intValue()) {
                                        if (touristCount.getOrderPeople().intValue() > touristTypeReq.getPeopleNum()) {
                                            throw new BusinessException(SystemError.CUSTOM_ORDER_4031, touristTypeReq.getLabel());
                                        }
                                        touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                                        touristCount.setModifiedId(userId);
                                        int updateCount = tripScheduleTouristCountMapper.updateById(touristCount);
                                        if (updateCount <= 0) {
                                            throw new BusinessException(SystemError.SYS_437);
                                        }
                                    }
                                }
                                //统计金额
                                totalPrice = totalPrice.add(serviceItemsReq.getSinglePrice().multiply(new BigDecimal(touristTypeReq.getPeopleNum())));
                            }
                            //批量新增旅客价格
                            Integer batch = tripScheduleTouristPriceMapper.insertBatchSomeColumn(touristPriceList);
                            if (batch < touristPriceList.size()) {
                                throw new BusinessException(SystemError.SYS_437);
                            }
                        }
                        packageServiceItemsList.add(packageServiceItems);
                    }
                    //批量新增服务项目
                    if (packageServiceItemsList.size() > 0) {
                        Integer batch = tripSchedulePackageServiceItemsMapper.insertBatchSomeColumn(packageServiceItemsList);
                        if (batch < packageServiceItemsList.size()) {
                            throw new BusinessException(SystemError.SYS_437);
                        }
                    }
                }
                //更新套餐总价和总人数
                freeQuotePackage.setTotalAmount(totalAmount);
                freeQuotePackage.setTotalPeople(pkgPeopleNum);
                int update = tripScheduleFreeQuotePackageMapper.updateById(freeQuotePackage);
                if (update <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
                //统计总团费
                totalGroupFee = totalGroupFee.add(totalAmount);
            }
        } else {
            if (req.getTripQuoteReqs() != null && req.getTripQuoteReqs().size() > 0) {
                //行程报价
                //新增团期旅客类型
                List<CustomizedQuotationTouristType> addList = new ArrayList<>();
                for (QuotationTouristTypeReq touristTypeReq : req.getTouristTypes()) {

                    //团期旅客类型统计
                    CustomizedTripScheduleTouristCount touristCount = tripScheduleTouristCountMapper.queryByTourist(touristTypeReq.getValue(), req.getScheduleId());
                    if (touristCount == null) {
                        //新增操作
                        touristCount = new CustomizedTripScheduleTouristCount();
                        touristCount.setId(SnowflakeIdWorker.nextId());
                        touristCount.setScheduleId(req.getScheduleId());
                        touristCount.setTouristTypeId(touristTypeReq.getValue());
                        touristCount.setTouristTypeName(touristTypeReq.getLabel());
                        touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                        touristCount.setOrderPeople(0);
                        touristCount.setCreateId(userId);
                        touristCount.setIsDeleted(0);
                        int insertCount = tripScheduleTouristCountMapper.insert(touristCount);
                        if (insertCount <= 0) {
                            throw new BusinessException(SystemError.SYS_437);
                        }
                    } else {
                        //修改操作
                        if (touristCount.getTotalPeople().intValue() != touristTypeReq.getPeopleNum().intValue()) {
                            if (touristCount.getOrderPeople().intValue() > touristTypeReq.getPeopleNum()) {
                                throw new BusinessException(SystemError.CUSTOM_ORDER_4031, touristTypeReq.getLabel());
                            }
                            touristCount.setTotalPeople(touristTypeReq.getPeopleNum());
                            touristCount.setModifiedId(userId);
                            int updateCount = tripScheduleTouristCountMapper.updateById(touristCount);
                            if (updateCount <= 0) {
                                throw new BusinessException(SystemError.SYS_437);
                            }
                        }
                    }

                    CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                    quotationTouristType.setId(SnowflakeIdWorker.nextId());
                    quotationTouristType.setScheduleId(req.getScheduleId());
                    quotationTouristType.setMainDataId(touristTypeReq.getValue());
                    quotationTouristType.setName(touristTypeReq.getLabel());
                    quotationTouristType.setAgeBegin(touristTypeReq.getAgeBegin());
                    quotationTouristType.setAgeEnd(touristTypeReq.getAgeEnd());
                    quotationTouristType.setPeopleNum(touristTypeReq.getPeopleNum());
                    quotationTouristType.setCreateId(userId);
                    quotationTouristType.setIsDeleted(0);
                    addList.add(quotationTouristType);
                    totalPeople += touristTypeReq.getPeopleNum();
                }
                //批量新增团期旅客类型
                if (addList.size() > 0) {
                    Integer batchAdd = quotationTouristTypeMapper.insertBatchSomeColumn(addList);
                    if (batchAdd < addList.size()) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                }
                List<TripQuoteReq> tripQuoteReqs = req.getTripQuoteReqs();
                for (TripQuoteReq tripQuoteReq : tripQuoteReqs) {
                    CustomizedTripScheduleDate date = EntityUtil.copy(tripQuoteReq, CustomizedTripScheduleDate.class);
                    date.setId(SnowflakeIdWorker.nextId());
                    date.setScheduleId(req.getScheduleId());
                    date.setTotalPeople(totalPeople);
                    date.setCurrencyId(tripQuoteReq.getCurrency().getValue());
                    date.setCurrency(tripQuoteReq.getCurrency().getText());
                    date.setExchangeRate(tripQuoteReq.getCurrency().getMarketExchangeRate());
                    date.setCreateId(userId);
                    date.setGmtCreate(LocalDateTime.now());
                    date.setIsDeleted(0);
                    int insert = tripScheduleDateMapper.insert(date);
                    if (insert <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                    //套餐总价
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    List<TripQuoteServiceItemsReq> serviceItems = tripQuoteReq.getServiceItems();
                    if (serviceItems != null && serviceItems.size() > 0) {
                        List<CustomizedTripScheduleQuoteServiceItems> serviceItemsList = new ArrayList<>();
                        for (TripQuoteServiceItemsReq serviceItemsReq : serviceItems) {
                            CustomizedTripScheduleQuoteServiceItems serviceItem = EntityUtil.copy(serviceItemsReq, CustomizedTripScheduleQuoteServiceItems.class);
                            serviceItem.setId(SnowflakeIdWorker.nextId());
                            serviceItem.setDateId(date.getId());
                            serviceItem.setScheduleId(req.getScheduleId());
                            serviceItem.setName(serviceItemsReq.getProjectName());
                            serviceItem.setServiceTypeName(serviceItemsReq.getServiceType().getLabel());
                            serviceItem.setMainDataId(serviceItemsReq.getServiceType().getValue());
                            BigDecimal totalPrice = serviceItemsReq.getSinglePrice().multiply(new BigDecimal(serviceItemsReq.getAmount()));
                            totalAmount = totalAmount.add(totalPrice);
                            serviceItem.setTotalPrice(totalPrice);
                            serviceItem.setTotalNum(serviceItemsReq.getAmount());
                            serviceItem.setCreateId(userId);
                            serviceItem.setGmtCreate(LocalDateTime.now());
                            serviceItem.setIsDeleted(0);
                            serviceItemsList.add(serviceItem);
                        }
                        //批量新增服务项目
                        Integer batch = tripScheduleQuoteServiceItemsMapper.insertBatchSomeColumn(serviceItemsList);
                        if (batch < serviceItemsList.size()) {
                            throw new BusinessException(SystemError.SYS_437);
                        }
                    }
                    //更新套餐总价
                    date.setTotalAmount(totalAmount);
                    int update = tripScheduleDateMapper.updateById(date);
                    if (update <= 0) {
                        throw new BusinessException(SystemError.SYS_437);
                    }
                    //统计总团费
                    totalGroupFee = totalGroupFee.add(totalAmount);
                }
            }
        }

        //判断最小订金是否合理
        if (req.getMinDeposit().compareTo(totalGroupFee.divide(new BigDecimal(totalPeople), 2, BigDecimal.ROUND_HALF_UP)) > 0) {
            throw new BusinessException(SystemError.CUSTOM_3015);
        }

        //团期金额统计
        CustomizedTripScheduleAmountStatistics amountStatistics = tripScheduleAmountStatisticsMapper.queryBySchedule(req.getScheduleId());
        if (amountStatistics == null) {
            //新增操作
            amountStatistics = new CustomizedTripScheduleAmountStatistics();
            amountStatistics.setId(SnowflakeIdWorker.nextId());
            amountStatistics.setScheduleId(req.getScheduleId());
            amountStatistics.setTotalFee(totalGroupFee);
            amountStatistics.setGroupFee(totalGroupFee);
            amountStatistics.setCollectionFee(BigDecimal.ZERO);
            amountStatistics.setAdjustFee(BigDecimal.ZERO);
            amountStatistics.setOtherFee(BigDecimal.ZERO);
            amountStatistics.setGroupFeeOrder(BigDecimal.ZERO);
            amountStatistics.setTotalPeople(totalPeople);
            amountStatistics.setCreateId(userId);
            amountStatistics.setIsDeleted(0);
            int insert = tripScheduleAmountStatisticsMapper.insert(amountStatistics);
            if (insert <= 0) {
                throw new BusinessException(SystemError.SYS_437);
            }
        } else {
            //修改操作
            if (totalGroupFee.compareTo(amountStatistics.getGroupFee().subtract(amountStatistics.getGroupFeeOrder())) < 0) {
                throw new BusinessException(SystemError.CUSTOM_ORDER_4032);
            }
            amountStatistics.setTotalFee(totalGroupFee);
            amountStatistics.setTotalPeople(totalPeople);
            amountStatistics.setModifiedId(userId);
            int update = tripScheduleAmountStatisticsMapper.updateById(amountStatistics);
            if (update <= 0) {
                throw new BusinessException(SystemError.SYS_437);
            }
        }
    }


    /**
     * 保存团队高级设置
     *
     * @param req
     * @param operateType
     * @return
     */
    private CustomizedTripScheduleAdvanced saveTripScheduleAdvanced(SaveTripScheduleBaseInfoReq req, int operateType) {
        TripScheduleAdvancedReq advancedReq = req.getAdvancedReq();
        CustomizedTripScheduleAdvanced advanced = null;
        if (operateType == NumberConstant.TWO.getValue()) {
            //修改
            if (req.getAdvancedReq().getId() != null) {
                advanced = tripScheduleAdvancedMapper.selectById(advancedReq.getId());
            }
        }
        advanced = EntityUtil.copy(advancedReq, CustomizedTripScheduleAdvanced.class);
        if (advancedReq.getNeedTripConsumption() != null) {
            advanced.setNeedTripConsumption(advancedReq.getNeedTripConsumption());
            if (advancedReq.getNeedTripConsumption().intValue() == NumberConstant.ONE.getValue()) {
                //需要小费
                advanced.setConsumptionId(advancedReq.getConsumptionId());
                advanced.setConsumptionName(advancedReq.getConsumptionName());
            }
        }
        if (advancedReq.getHasTeaParty() != null) {
            advanced.setHasTeaParty(advancedReq.getHasTeaParty());
            if (advancedReq.getHasTeaParty().intValue() == NumberConstant.ONE.getValue()) {
                //需要茶会
                advanced.setTeaPartyLocId(advancedReq.getTeaPartyLocId());
                advanced.setTeaPartyDate(advancedReq.getTeaPartyDate());
                advanced.setTeaPartyTime(advancedReq.getTeaPartyTime());
                advanced.setTeaPartyRemark(advancedReq.getTeaPartyRemark());
            }
        }
        if (advancedReq.getBadgeColorId() != null) {
            try {
                MainDataFieldDataDTO colorDTO = mainDataFieldDataService.queryFieldData(advancedReq.getBadgeColorId());
                if (colorDTO != null) {
                    advanced.setBadgeColorId(advancedReq.getBadgeColorId());
                    advanced.setBadgeColor(colorDTO.getFieldValue());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        if (StringUtils.isNotBlank(advancedReq.getGuideRequirement())) {
            advanced.setGuideRequirement(advancedReq.getGuideRequirement());
        }
        if (advancedReq.getCollectionPlaceId() != null && advancedReq.getCollectionAreaId() != null) {
            try {
                MainDataCollectionPlaceIdReq placeIdReq = new MainDataCollectionPlaceIdReq();
                placeIdReq.setId(advancedReq.getCollectionPlaceId());
                MainDataCollectionPlaceDTO placeDTO = mainDataCollectionPlaceService.query(placeIdReq);
                AreaQueryIdReq areaQueryIdReq = new AreaQueryIdReq();
                areaQueryIdReq.setId(advancedReq.getCollectionAreaId());
                AreaTreeListDTO collectionPlaceDTO = areaService.queryById(areaQueryIdReq);
                if (collectionPlaceDTO != null && placeDTO != null) {
                    advanced.setCollectionPlaceId(advancedReq.getCollectionPlaceId());
                    advanced.setCollectionPlace(placeDTO.getCollectionPlaceName());
                    advanced.setCollectionAreaId(advancedReq.getCollectionAreaId());
                    advanced.setCollectionArea(collectionPlaceDTO.getName());
                    advanced.setCollectionTime(advancedReq.getCollectionTime());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        if (advancedReq.getDissolutionAreaId() != null && advancedReq.getDissolutionPlaceId() != null) {
            try {
                AreaQueryIdReq areaQueryIdReq = new AreaQueryIdReq();
                areaQueryIdReq.setId(advancedReq.getDissolutionAreaId());
                AreaTreeListDTO dissolutionAreaDTO = areaService.queryById(areaQueryIdReq);
                if (dissolutionAreaDTO != null) {
                    advanced.setDissolutionAreaId(advancedReq.getDissolutionAreaId());
                    advanced.setDissolutionArea(dissolutionAreaDTO.getName());
                }
                MainDataCollectionPlaceIdReq placeIdReq = new MainDataCollectionPlaceIdReq();
                placeIdReq.setId(advancedReq.getDissolutionPlaceId());
                MainDataCollectionPlaceDTO placeDTO = mainDataCollectionPlaceService.query(placeIdReq);
                if (placeDTO != null) {
                    advanced.setDissolutionPlaceId(advancedReq.getDissolutionPlaceId());
                    advanced.setDissolutionPlace(placeDTO.getCollectionPlaceName());
                    advanced.setDissolutionTime(advancedReq.getDissolutionTime());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        advanced.setDepartureConsulation(advancedReq.getDepartureConsulation());
        advanced.setDepartureTime(advancedReq.getDepartureTime());
        advanced.setGoArriveDateType(advancedReq.getGoArriveDateType());
        advanced.setGoArriveTime(advancedReq.getGoArriveTime());
        if (advancedReq.getReturnTrafficTypeId() != null) {
            try {
                MainDataFieldDataDTO returnTrafficTypeDTO2 = mainDataFieldDataService.queryFieldData(advancedReq.getDepartureTrafficTypeId());
                if (returnTrafficTypeDTO2 != null) {
                    advanced.setDepartureTrafficTypeId(advancedReq.getDepartureTrafficTypeId());
                    advanced.setDepartureTrafficType(returnTrafficTypeDTO2.getFieldValue());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        advanced.setReturnConsulation(advancedReq.getReturnConsulation());
        advanced.setReturnTime(advancedReq.getReturnTime());
        advanced.setReturnArriveDateType(advancedReq.getReturnArriveDateType());
        advanced.setReturnArriveTime(advancedReq.getReturnArriveTime());
        if (advancedReq.getReturnTrafficTypeId() != null) {
            try {
                MainDataFieldDataDTO returnTrafficTypeDTO = mainDataFieldDataService.queryFieldData(advancedReq.getReturnTrafficTypeId());
                if (returnTrafficTypeDTO != null) {
                    advanced.setReturnTrafficTypeId(advancedReq.getReturnTrafficTypeId());
                    advanced.setReturnTrafficType(returnTrafficTypeDTO.getFieldValue());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        if (advancedReq.getDeductionRulesId() != null) {
            try {
                MainDataDeductionRulesIdReq dataDeductionRulesIdReq = new MainDataDeductionRulesIdReq();
                dataDeductionRulesIdReq.setId(advancedReq.getDeductionRulesId());
                MainDataDeductionRulesDTO deductionRules = dataDeductionRulesService.query(dataDeductionRulesIdReq);
                if (deductionRules != null) {
                    advanced.setDeductionRulesId(advancedReq.getDeductionRulesId());
                    advanced.setDeductionRulesName(deductionRules.getDeductionRules());
                }
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_417);
            }
        }
        return advanced;
    }

    /**
     * 封装团期属性
     *
     * @param req
     * @param tripSchedule
     * @return
     */
    private CustomizedTripSchedule setTripScheduleAttr(SaveTripScheduleBaseInfoReq req, CustomizedTripSchedule tripSchedule) {
        if (req.getInquiryId() != null) {
            CustomizedInquiry inquiry = inquiryMapper.selectById(req.getInquiryId());
            if (inquiry != null) {
                tripSchedule.setInquiryId(req.getInquiryId());
                tripSchedule.setInquiryNumber(inquiry.getInquiryNumber());
                tripSchedule.setInquiryTitle(inquiry.getInquiryTitle());
                if (inquiry.getQuotationId() != null) {
                    CustomizedQuotation quotation = quotationMapper.selectById(inquiry.getQuotationId());
                    if (quotation != null) {
                        tripSchedule.setQuotationId(inquiry.getQuotationId());
                        tripSchedule.setQuotationNumber(quotation.getQuotationNumber());
                        tripSchedule.setQuotationTitle(quotation.getQuotationTitle());
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(req.getInquiryInfo())) {
            QueryWrapper<CustomizedInquiry> inquiryWrapper = new QueryWrapper<>();
            inquiryWrapper.like("inquiry_number", req.getInquiryInfo());
            inquiryWrapper.or();
            inquiryWrapper.like("inquiry_title", req.getInquiryInfo());
            inquiryWrapper.eq("is_deleted", 0);
            CustomizedInquiry inquiry = inquiryMapper.selectOne(inquiryWrapper);
            if (inquiry != null) {
                tripSchedule.setInquiryId(req.getInquiryId());
                tripSchedule.setInquiryNumber(inquiry.getInquiryNumber());
                tripSchedule.setInquiryTitle(inquiry.getInquiryTitle());
            }
        }
        if (req.getQuotationId() != null) {
            CustomizedQuotation quotation = quotationMapper.selectById(req.getQuotationId());
            if (quotation != null) {
                tripSchedule.setQuotationId(req.getQuotationId());
                tripSchedule.setQuotationNumber(quotation.getQuotationNumber());
                tripSchedule.setQuotationTitle(quotation.getQuotationTitle());
            }
        }
        if (req.getBigClientId() != null) {
            Result<SysBigClientDTO> result = bigClientService.query(req.getBigClientId());
            if (result.getCode() == 0) {
                tripSchedule.setBigClientName(result.getData().getCnName());
                tripSchedule.setBigClientId(req.getBigClientId());
            }
        }
        tripSchedule.setName(req.getName());
        tripSchedule.setDepartType(req.getDepartType());
        tripSchedule.setNeedInsurance(req.getNeedInsurance());
        if (StringUtils.isNotBlank(req.getSubtitle())) {
            tripSchedule.setSubtitle(req.getSubtitle());
        }
        try {
            MainDataFieldDataDTO groupTypeDTO = mainDataFieldDataService.queryFieldData(req.getGroupTypeId());
            if (groupTypeDTO != null) {
                tripSchedule.setGroupTypeId(req.getGroupTypeId());
                tripSchedule.setGroupTypeName(groupTypeDTO.getFieldValue());
            }
            MainDataTourGroupCodeUpdateStatusReq groupCodeUpdateStatusReq = new MainDataTourGroupCodeUpdateStatusReq();
            groupCodeUpdateStatusReq.setId(req.getTourTypeId());
            Result<MainDataTourGroupCodeQueryDTO> query = tourGroupCodeService.query(groupCodeUpdateStatusReq);
            if (query != null && query.isSuccess()){
                tripSchedule.setTourTypeId(req.getTourTypeId());
                tripSchedule.setTourTypeName(query.getData().getTourGroupName());
            }
            AreaQueryIdReq destinationReq = new AreaQueryIdReq();
            destinationReq.setId(req.getDestinationId());
            AreaTreeListDTO destinationDTO = areaService.queryById(destinationReq);
            if (destinationDTO != null) {
                tripSchedule.setDestinationId(req.getDestinationId());
                tripSchedule.setDestination(destinationDTO.getName());
            }
            AreaQueryIdReq departurePlaceReq = new AreaQueryIdReq();
            departurePlaceReq.setId(req.getDeparturePlaceId());
            AreaTreeListDTO departurePlace = areaService.queryById(departurePlaceReq);
            if (departurePlace != null) {
                tripSchedule.setDeparturePlaceId(req.getDeparturePlaceId());
                tripSchedule.setDeparturePlace(departurePlace.getName());
            }
            UserDTO chargePerson = sysUserService.queryCacheUser(req.getChargePersonId());
            if (chargePerson != null) {
                tripSchedule.setChargePersonId(req.getChargePersonId());
                tripSchedule.setChargePersonNumber(chargePerson.getEmployeeNumber());
                tripSchedule.setChargePersonName(chargePerson.getFullName());
            }
            if (req.getOpId() != null) {
                UserDTO op = sysUserService.queryCacheUser(req.getOpId());
                if (op != null) {
                    tripSchedule.setOpId(req.getOpId());
                    tripSchedule.setOpNumber(op.getEmployeeNumber());
                    tripSchedule.setOpName(op.getFullName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(SystemError.SYS_417);
        }
        if (req.getDepartureDate() != null) {
            LocalDateTime dateTime = DateUtil.parse(DateUtil.fmtLocalDate(req.getDepartureDate(), "yyyy-MM-dd 00:00:00"));
            tripSchedule.setDepartureDate(dateTime);
        }
        tripSchedule.setTravelDays(req.getTravelDays());
        tripSchedule.setNightDays(req.getNightDays());
        if (StringUtils.isNotBlank(req.getInternalSummary())) {
            tripSchedule.setInternalSummary(req.getInternalSummary());
        }
        if (StringUtils.isNotBlank(req.getReceptionInstructions())) {
            tripSchedule.setReceptionInstructions(req.getReceptionInstructions());
        }
        if (StringUtils.isNotBlank(req.getCustomerRights())) {
            tripSchedule.setCustomerRights(req.getCustomerRights());
        }
        if (StringUtils.isNotBlank(req.getShopNotice())) {
            tripSchedule.setShopNotice(req.getShopNotice());
        }
        tripSchedule.setNeedInsurance(req.getNeedInsurance());
        tripSchedule.setNeedVisa(req.getNeedVisa());
        return tripSchedule;
    }
}
